Your integration reads order events from a Service Bus queue. Two consumers pick up created and paid for the same order, the faster one finishes first, and your downstream system sees a payment for an order that doesn’t exist yet. Azure Service Bus sessions are the built-in fix: messages that share a session ID are handed to one receiver at a time, in the order they arrived, while other sessions run in parallel. This article explains how sessions and session locks work, what they cost you in throughput and design freedom, and how to decide whether you need them at all. It’s based on Microsoft Learn as of December 2026 and on a small simulation run for this post; see What was tested for this post for exactly what was and wasn’t run.

Short answer
- A session is a group of messages with the same
SessionId. The sender sets it; Service Bus doesn’t define what it means. Use something like an order ID (Message sessions). - A receiver that accepts a session holds an exclusive lock on it. It gets that session’s messages in order, including ones that arrive later, and no other receiver can take them until the lock is released or expires.
- FIFO is per session, not per queue. Different sessions are processed in parallel by different receivers.
- You need sessions when messages must be processed in order, not just received in order. Microsoft is explicit that sequence numbers alone don’t give you processing order (Message sequencing).
- Plan up front. Sessions need the Standard or Premium tier, and you can only turn them on when you create the queue or subscription (Enable message sessions).
What a Service Bus session is
A session is just a label on messages. The sender sets the session ID property (it maps to the AMQP group-id), and every message with the same ID belongs to the same session. Service Bus doesn’t decide where a sequence starts or ends. A session exists while at least one message with that ID is in the entity, and there’s no built-in expiry: in theory, a message sent a year later with the same ID joins the same session. If your workflow has a clear start and end, mark them yourself, for example in a message property (Learn).
Sessions are a property of a queue or a topic subscription, and they change the entity’s contract:
- Once sessions are on, clients can no longer send or receive regular messages on that entity. Every message needs a session ID, and receivers must accept a session. Peeking still works.
- A message that reaches a session-enabled entity by auto-forwarding without a session ID is dead-lettered with the reason
Session ID is null(Auto-forwarding, dead-letter reasons). - You can’t switch sessions on or off later. Changing your mind means a new queue or subscription.
- The Basic tier doesn’t support sessions; Standard and Premium do.
Sequence numbers versus sessions
Every message gets a broker-assigned, gap-free, increasing sequence number, so Service Bus always knows the true arrival order. That guarantees the order messages are queued and handed out, not the order they’re processed. Microsoft’s own example: with two consumers, consumer 1 takes message 1, consumer 2 takes message 2 and then 3, and both finish before message 1. The processing order is 2, 3, 1. If messages only need to be retrieved in order, you don’t need sessions. If they need to be processed in order, you do (Message sequencing and timestamps).
How the session lock works
A session receiver accepts a session, either a specific session ID or the next available one. From then on:
- It owns the whole session. The receiver holds an exclusive lock on every message with that session ID, including messages that arrive later. Only one receiver can hold a session at a time, and the lock is managed inside Service Bus, so receivers can run on different machines (Learn).
- The session lock is an umbrella over message locks. Messages are still received in peek-lock mode and settled one by one (complete, abandon, dead-letter), but always within the session’s order.
- An abandoned message comes straight back. The next receive returns the same message again. That’s what keeps the order, and it’s also why one failing message holds up the rest of its session.
- The lock has a timeout. Locks follow the queue or subscription’s lock duration: 1 minute by default, 5 minutes at most (Message locks and settlement). For longer work, renew the lock or use the SDK’s automatic lock renewal. The .NET session processor documents its renewal setting as needing to exceed the queue’s
LockDuration(ServiceBusSessionProcessorOptions). - Release it when you’re done. The lock ends when the receiver closes the session or the lock expires. Learn compares it to an exclusive file lock: close the session as soon as you don’t expect more messages.
- Idle sessions are released on a timer. Session processors and the Functions trigger close a session after a session idle timeout with no new message and move on to another one. Learn notes that if this timeout is shorter than the message lock duration and nothing happens on the message in time, the session expires and the message lock is lost (Learn).
Two errors tell you the lock is involved. SessionCannotBeLocked means another receiver holds the session; you can accept it once that lock expires. SessionLockLost means your lock expired on the service side, so you can no longer settle the messages you received under it (Service Bus exceptions).
How sessions change the delivery count
Delivery count works slightly differently inside a session. This matters because MaxDeliveryCount (default 10) decides when a message is dead-lettered (Learn):
| What happened | Delivery count goes up? |
|---|---|
| Session lock expired (timeout) | Yes |
| Session closed with messages not completed | No |
| Messages completed, session closed | N/A: messages are gone |
So a receiver that’s too slow and doesn’t renew its lock burns through delivery attempts even though your code never threw an exception. The simulation below shows that happening.
A simulation: what the lock does and doesn’t protect
To make these rules concrete, I wrote a small standard-library Python script that models them. It’s a simulation, not Service Bus. It calls no Azure API, time is in abstract ticks, and it encodes the behaviour described above: competing consumers take the next message by sequence number; a session receiver owns one session and takes its messages in order; an abandoned message is served again first; and an expired session lock raises the delivery count and frees the session for another receiver. One simplification: an idle receiver picks the session whose oldest message has the lowest sequence number. Service Bus doesn’t document how it picks the next available session.
The input is nine interleaved events for three orders (A, B and C: created, paid, shipped). order-A created takes longest. Five scenarios ran on Python 3.13.5:
| Scenario | Result |
|---|---|
| 1. No sessions, 3 receivers | A paid finished before A created |
| 2. Sessions, 3 receivers | Order kept; same finish time as 1 |
| 3. Sessions, B paid always fails | B blocked 3 attempts, then B paid dead-lettered and B shipped ran anyway |
| 4. Sessions, slow message, lock 4 ticks, no renewal | 5 runs whose complete failed; A created dead-lettered |
| 5. Same as 4 with lock renewal | Order kept, nothing dead-lettered |
Summary output (simulation, run locally on 3 December 2026)
SUMMARY
scenario 1: finished t=5, completed=9, dead-lettered=0, order violations=1, gaps after DLQ=0, failed completes=0
scenario 2: finished t=5, completed=9, dead-lettered=0, order violations=0, gaps after DLQ=0, failed completes=0
scenario 3: finished t=10, completed=8, dead-lettered=1, order violations=0, gaps after DLQ=1, failed completes=0
scenario 4: finished t=17, completed=8, dead-lettered=1, order violations=0, gaps after DLQ=2, failed completes=5
scenario 5: finished t=9, completed=9, dead-lettered=0, order violations=0, gaps after DLQ=0, failed completes=0What this shows, in plain terms:
- Without sessions, order breaks as soon as processing times differ (scenario 1). Retrieval was in perfect sequence order; processing wasn’t. This is Microsoft’s 2-3-1 example with real-looking data.
- Sessions keep order without giving up parallelism across orders (scenario 2). Each order is one lane; three receivers work on three lanes at once. In this tiny input it finished at the same tick as scenario 1. With fewer receivers than busy sessions, sessions wait their turn.
- Sessions don’t stop a poison message from breaking your business order (scenario 3). The failing message blocks its session until it reaches the max delivery count; then it’s dead-lettered and the session continues, so shipped is processed for an order whose payment never was. Microsoft documents exactly this continue-after-DLQ behaviour, and warns that resubmitting a dead-lettered message gives it a new sequence number, so its original position is lost (Learn). Your handler must check preconditions, not assume them.
- A lost lock means work done twice (scenario 4). The first receiver finished its work, but the lock had expired, so it couldn’t complete the message; another receiver ran it again. After three expiries the message was dead-lettered even though no code failed. Scenario 5 is the same input with lock renewal, and everything completes once.
Scenario 3 log (simulation)
=== 3. Sessions on, order-B paid always fails (poison)
receivers=2 sessions=on max_delivery=3 lock_duration=99 auto_renew=True
t= 0 R1 accepted session order-A
t= 0 R1 started order-A created (seq 1, delivery 1)
t= 0 R2 accepted session order-B
t= 0 R2 started order-B created (seq 2, delivery 1)
t= 1 R2 completed order-B created (seq 2)
t= 1 R2 started order-B paid (seq 5, delivery 1)
t= 2 R2 order-B paid failed, abandoned (delivery 1); served again next
t= 2 R2 started order-B paid (seq 5, delivery 2)
t= 3 R1 completed order-A created (seq 1)
t= 3 R2 order-B paid failed, abandoned (delivery 2); served again next
t= 3 R1 started order-A paid (seq 3, delivery 1)
t= 3 R2 started order-B paid (seq 5, delivery 3)
t= 4 R1 completed order-A paid (seq 3)
t= 4 R2 order-B paid failed, delivery 3 -> dead-lettered; session continues
t= 4 R1 started order-A shipped (seq 6, delivery 1)
t= 4 R2 started order-B shipped (seq 8, delivery 1)
t= 5 R1 completed order-A shipped (seq 6)
t= 6 R2 completed order-B shipped (seq 8)
t= 6 R1 released order-A (idle)
t= 6 R1 accepted session order-C
t= 6 R1 started order-C created (seq 4, delivery 1)
t= 7 R2 released order-B (idle)
t= 8 R1 completed order-C created (seq 4)
t= 8 R1 started order-C paid (seq 7, delivery 1)
t= 9 R1 completed order-C paid (seq 7)
t= 9 R1 started order-C shipped (seq 9, delivery 1)
t=10 R1 completed order-C shipped (seq 9)
finished at t=10; completed=8 dead-lettered=1 runs whose complete failed (work done twice or wasted)=0
per-session order: OK
gap: order-B: shipped completed although paid (seq 5) was dead-letteredThe full script is at the end of this article, after What was tested for this post.
Session state: resume where the last receiver stopped
Each session can carry a small, opaque blob stored by the broker: the session state. A receiver reads it when it accepts the session and writes it as it makes progress, so if the process dies, the next receiver to accept the session picks up the recorded position instead of starting over. Facts from Learn and the quotas page:
- The state can be as large as one message: 256 KB on Standard and, per the sessions page, 100 MB on Premium. You can also store a pointer to a database record instead.
- It stays until you clear it (set it to null), even after every message in the session has been consumed. It counts toward the entity’s storage quota, so clean up finished sessions.
- A queue or subscription can hold at most 1,000,000 session states, and a session ID can be up to 128 characters.
- Getting and setting session state are billed operations on the Standard tier (Service Bus pricing).
Session state doesn’t replace idempotency. Writing state and completing a message are separate calls, so a crash between them can still cause a message to be processed twice. Treat the state as a progress marker, and make the handler safe to repeat.
Behaviours that change your design
- One expired message expires the whole session. On session-enabled entities, messages are locked at session level. If any message in a session passes its time-to-live, all messages in that session expire, and are dropped or dead-lettered depending on the entity’s dead-letter-on-expiration setting. Learn adds that this only happens while there’s an active listener (Message sessions). Set TTLs with this in mind.
- A session-enabled entity can’t auto-forward. It can be the destination of auto-forwarding, but not the source; setting
ForwardToon a session-enabled queue or subscription fails (Auto-forwarding). - On partitioned entities the session ID is the partition key. All of a session’s messages go to one partition, which is how ordering and session state stay consistent. If you also set
PartitionKey, it must equal the session ID, or the send fails. You also can’t send to different sessions in one transaction on a partitioned entity, and if that partition is unavailable, operations for its sessions fail rather than move elsewhere (Partitioning). - Request-reply is the other session use case. A requester sends with a reply session ID, and accepts that session on a session-enabled reply queue to receive only its own responses (Learn). This article focuses on FIFO.
When do you actually need sessions?
Sessions are a trade-off. They serialise each key’s messages, add a lock to manage, and tie a slow or failing message to everything behind it. Azure’s Sequential Convoy pattern describes the same balance: per-group FIFO with scale-out across groups, and it calls Service Bus sessions the built-in way to implement it on Azure (Sequential Convoy pattern). Use this guide before you turn them on:

| Situation | Better fit | Why |
|---|---|---|
| Order doesn’t affect the result | No sessions | Competing consumers scale more simply |
| Telemetry or clickstream you replay | Event Hubs, partition key | Ordered per partition, with retention |
| Latest state wins | Version check | Handler skips older versions |
| Steps for one entity must run in order | Sessions | Per-key FIFO, parallel across keys |
| Everything in strict global order | One receiver | Only way; doesn’t scale |
Two notes on the alternatives. A version check means the producer stamps each update with a version or timestamp, and the consumer ignores anything older than what it has stored. It works for state updates (address changed), not for steps that must all run (created, paid, shipped). For streams, the trade-offs between brokers are covered in Event Hubs vs Service Bus vs Event Grid, and partition-level ordering in Event Hubs partitions and consumer groups.
Choosing the session ID
The session ID is your unit of ordering and your unit of parallelism at the same time. The Sequential Convoy guidance warns that a key that’s too coarse limits parallelism, and one that’s too fine gives no ordering benefit (Learn). Here’s how common choices compare (my analysis based on that guidance):
| Session ID | Order kept across | Parallelism | Watch out for |
|---|---|---|---|
| Order ID | One order’s steps | High | No order across orders |
| Customer ID | All of a customer’s orders | Medium | Busy customers queue up |
| Tenant or region | A whole tenant | Low | One hot lane |
| A constant | Everything | None | Single-threaded queue |
| New GUID per message | Nothing | Maximum | Sessions with no benefit |
Pick the narrowest key whose messages really depend on each other. The pattern guidance also asks producers to set the key correctly on every message, because a wrong key quietly puts a message into another group’s sequence.
Using sessions from Azure Functions, Logic Apps and SDK workers
First, the entity. This is the az CLI form from Learn with a few extra settings. Parameter names were checked against az --help; the commands weren’t run.
Create a session-enabled queue and subscription (example, not executed)
# Example, not executed. Session support is fixed at creation time.
az servicebus queue create \
--resource-group rg-integration \
--namespace-name sb-orders-demo \
--name order-events \
--enable-session true \
--lock-duration PT1M \
--max-delivery-count 5
az servicebus topic subscription create \
--resource-group rg-integration \
--namespace-name sb-orders-demo \
--topic-name orders \
--name billing \
--enable-session true
# Is an existing queue session-enabled?
az servicebus queue show \
--resource-group rg-integration \
--namespace-name sb-orders-demo \
--name order-events \
--query requiresSessionThe same queue in Bicep (example, not deployed; compiles with Bicep CLI 0.48.1)
// Example, not deployed. A Standard namespace with a session-enabled queue.
param location string = resourceGroup().location
param namespaceName string
resource sb 'Microsoft.ServiceBus/namespaces@2024-01-01' = {
name: namespaceName
location: location
sku: {
name: 'Standard' // Basic doesn't support sessions
tier: 'Standard'
}
properties: {
disableLocalAuth: true // Microsoft Entra ID only, no SAS keys
}
}
resource orderEvents 'Microsoft.ServiceBus/namespaces/queues@2024-01-01' = {
parent: sb
name: 'order-events'
properties: {
requiresSession: true // can only be set when the queue is created
lockDuration: 'PT1M' // message and session locks; maximum PT5M, renew for longer work
maxDeliveryCount: 5 // then the message is dead-lettered and the session moves on
deadLetteringOnMessageExpiration: true
}
}Azure Functions
The Service Bus trigger supports session-enabled queues and subscriptions from extension version 3.1.0. Set IsSessionsEnabled (C#), isSessionsEnabled (function.json) or is_sessions_enabled (Python v2 decorator) to true (Service Bus trigger). Session concurrency is controlled in host.json, not by maxConcurrentCalls, which is ignored for session triggers (host.json settings):
maxConcurrentSessions: sessions handled at once per scaled instance. Default 8.sessionIdleTimeout: how long to wait for the next message in the current session before closing it and moving to another. It defaults toclientRetryOptions.tryTimeout(1 minute), and the wait starts after the previous invocation completes. If sessions are short, a lower value stops instances waiting on empty sessions.maxAutoLockRenewalDuration: how long the lock is renewed automatically. Default 5 minutes.
Python v2 session trigger (example, not deployed)
# Example, not deployed. Python v2 programming model, azure-functions 2.4.0.
import json
import logging
import azure.functions as func
app = func.FunctionApp()
@app.service_bus_queue_trigger(arg_name="msg", queue_name="order-events",
connection="ServiceBusConnection", is_sessions_enabled=True)
def process_order_event(msg: func.ServiceBusMessage):
event = json.loads(msg.get_body().decode("utf-8"))
logging.info("session %s seq %s: %s", msg.session_id, msg.sequence_number, event)
# Keep this idempotent: a lost session lock means the same message can run again.host.json (example)
{
"version": "2.0",
"extensions": {
"serviceBus": {
"maxConcurrentSessions": 8,
"sessionIdleTimeout": "00:00:30",
"maxAutoLockRenewalDuration": "00:05:00"
}
}
}Learn’s decorator table for the Python v2 model didn’t list the sessions argument when I checked; is_sessions_enabled is present in the azure-functions 2.4.0 library, and importing the file above produced a trigger binding with isSessionsEnabled: true. With scale-out, each active session can map to a concurrent execution (Learn), so the plan you run on matters; see Azure Functions hosting plans for integration workloads.
Logic Apps
Logic Apps implements sessions as the sequential convoy pattern, for both Consumption and Standard (Send related messages in order):
- Standard workflows have a template: Azure Service Bus: Process related messages from a session-enabled queue for the same workflow instance – Sequential convoy pattern. For Consumption, the article says no designer template is available any more (the former Correlated in-order delivery template is on GitHub), so you build the workflow by hand.
- The trigger’s Session id is set to Next available, so each run locks one session and processes its messages.
- A parallel Until loop renews the session lock while messages remain, with a default timeout of one hour (
PT1H). - The connector caches up to 1,500 unique sessions per entity; beyond that, old sessions are removed from the cache (Service Bus connector).
- Occasional session cannot be accepted or session not found errors are expected, because the session receiver lives in memory on one connector instance. The message stays in Service Bus and the next run tries again.
Session-enabled workflows still need a plan for messages that keep failing. The peek-lock, retry and dead-letter handling is covered in Logic Apps Service Bus poison messages.
SDK workers (.NET and Python)
For a worker you host yourself, in App Service, a container or a VM, use the session processor (.NET) or a session receiver (Python). In .NET, ServiceBusSessionProcessor defaults to MaxConcurrentSessions = 8 and MaxConcurrentCallsPerSession = 1, and total concurrency is the product of the two (ServiceBusSessionProcessor). Raising calls per session lets one session’s messages run at the same time, which defeats in-order processing, so leave it at 1 when order matters (my inference from that definition).
C# session processor (example, not compiled or executed)
// Example, not compiled or executed. Azure.Messaging.ServiceBus + Azure.Identity.
await using var client = new ServiceBusClient("<namespace>.servicebus.windows.net", new DefaultAzureCredential());
var options = new ServiceBusSessionProcessorOptions
{
MaxConcurrentSessions = 8, // sessions in parallel (default 8)
MaxConcurrentCallsPerSession = 1, // keep 1 for in-order processing (default 1)
SessionIdleTimeout = TimeSpan.FromSeconds(30),
MaxAutoLockRenewalDuration = TimeSpan.FromMinutes(10),
AutoCompleteMessages = false
};
await using ServiceBusSessionProcessor processor = client.CreateSessionProcessor("order-events", options);
processor.ProcessMessageAsync += async args =>
{
BinaryData state = await args.GetSessionStateAsync(); // null if never set
await HandleAsync(args.SessionId, args.Message); // idempotent business logic
await args.CompleteMessageAsync(args.Message);
await args.SetSessionStateAsync(BinaryData.FromString(args.Message.SequenceNumber.ToString()));
};
processor.ProcessErrorAsync += args =>
{
Console.WriteLine($"{args.ErrorSource}: {args.Exception.Message}"); // SessionLockLost shows up here
return Task.CompletedTask;
};
await processor.StartProcessingAsync();The member names above come from the processor options and ProcessSessionMessageEventArgs reference pages. The Python version uses NEXT_AVAILABLE_SESSION, an AutoLockRenewer and the session state methods from the azure-servicebus library:
Python session receiver (example, not executed against Service Bus)
# Example, not executed against Service Bus. Python, azure-servicebus 7.15.0 + azure-identity.
# Sender: every message for one order carries the same session ID.
# Receiver: accept the next available session, read its messages in order, keep progress in session state.
import json
from azure.identity import DefaultAzureCredential
from azure.servicebus import (AutoLockRenewer, NEXT_AVAILABLE_SESSION, ServiceBusClient,
ServiceBusMessage)
NAMESPACE = "<your-namespace>.servicebus.windows.net"
QUEUE = "order-events" # created with sessions enabled
def handle(event):
print("processing", event) # your idempotent business logic goes here
with ServiceBusClient(NAMESPACE, DefaultAzureCredential()) as client:
with client.get_queue_sender(QUEUE) as sender:
for step in ("created", "paid", "shipped"):
body = json.dumps({"orderId": "A-1001", "event": step})
sender.send_messages(ServiceBusMessage(body, session_id="A-1001"))
renewer = AutoLockRenewer(max_lock_renewal_duration=300) # renews the session lock for up to 5 minutes
with client.get_queue_receiver(QUEUE, session_id=NEXT_AVAILABLE_SESSION,
max_wait_time=30, auto_lock_renewer=renewer) as receiver:
session = receiver.session
state = json.loads(session.get_state() or b"{}") # where the last owner stopped
for msg in receiver: # messages of this session, in order
handle(json.loads(str(msg)))
receiver.complete_message(msg)
state["last_sequence"] = msg.sequence_number
session.set_state(json.dumps(state))
renewer.close()Learn’s performance guidance recommends reusing one ServiceBusClient and disposing each session receiver when its session is finished, because a session receiver lives only as long as its session (performance guidance).
Security, reliability, monitoring and cost
- Security. Sessions don’t change how you authenticate. Use Microsoft Entra ID with the built-in roles (Azure Service Bus Data Sender, Data Receiver) and consider disabling local SAS authentication (Learn); the Bicep example does. Session IDs and session state live in the broker and show up in tooling, so don’t put secrets or personal data in them. The same no-secrets approach is covered in securing data pipelines with managed identity and Key Vault.
- Reliability. Keep handlers idempotent: lock loss and crashes can still repeat a message. Renew locks for work that can exceed the lock duration. Check preconditions in each step, because a dead-lettered message lets the rest of its session continue. Decide what replay means before you need it, since a resubmitted message loses its place in the sequence.
- Monitoring. Azure Monitor’s Service Bus metrics are per entity, not per session: watch active, dead-lettered and abandoned message counts (metrics reference). To see which sessions have work or stored state, use the session listing APIs (Python
list_queue_sessions, .NETGetMessageSessionsAsync), and logSessionLockLostandSessionCannotBeLockedfrom your error handler. - Cost. Sessions need Standard or Premium; Basic doesn’t support them. On Standard you pay per operation, and Microsoft lists session state get/set as operations and bills message lock renewals too; Premium doesn’t charge per operation up to its purchased capacity (Service Bus pricing). The bigger cost lever is usually compute: more active sessions means more concurrent executions. No prices are quoted here; use the pricing page for your region.
What was tested for this post
- Run locally:
session_sim.py, the simulation above, with Python 3.13.5. Its output is reproduced as captured. It models documented behaviour; it isn’t Service Bus and its ticks aren’t real timings. - Checked, not executed against Azure: the Python receiver example compiles, and every SDK name it uses exists in azure-servicebus 7.15.0. The Functions example was imported with azure-functions 2.4.0 and produced a binding with
isSessionsEnabled: true; host.json parses as JSON. The Bicep file compiles with Bicep CLI 0.48.1. The az parameter names were checked against Azure CLI 2.93.0--help, and the shell snippet withbash -n. - Not executed: nothing touched a real Service Bus namespace. No messages were sent or received, no Logic App or function was deployed, and the C# example wasn’t compiled because no .NET SDK was available.
- My inference, not stated on Learn: the advice to keep
MaxConcurrentCallsPerSessionat 1, the session ID comparison table, and the simulation’s choice of next session.
The simulation script
Standard library only. Save it as session_sim.py and run python3 session_sim.py.
"""session_sim.py - a SIMULATION of Service Bus session semantics. It is not Service Bus and calls no Azure API.
Standard library only. Time is in abstract "ticks", not seconds. The model follows the behaviour Microsoft Learn
documents for message sessions:
* without sessions, competing consumers take the next message in sequence order and can finish out of order;
* with sessions, a receiver holds an exclusive lock on one session and gets that session's messages in order,
while other receivers work on other sessions in parallel;
* an abandoned message is served again first, so a failing message blocks its session until it exceeds
the max delivery count and is dead-lettered;
* if a session lock expires (no renewal), the delivery count goes up and another receiver can take the session.
Simplification: an idle receiver accepts the session whose oldest message has the lowest sequence number.
The real "next available session" choice is made by the broker and isn't documented as sequence-ordered.
"""
import sys
def stream(poison=None, slow=None):
# (sequence number, session ID, label, ticks to process); interleaved as a sender would produce them
rows = [(1, "order-A", "created", 3), (2, "order-B", "created", 1), (3, "order-A", "paid", 1),
(4, "order-C", "created", 2), (5, "order-B", "paid", 1), (6, "order-A", "shipped", 1),
(7, "order-C", "paid", 1), (8, "order-B", "shipped", 2), (9, "order-C", "shipped", 1)]
out = []
for seq, sid, label, cost in rows:
if slow and seq == slow[0]:
cost = slow[1]
out.append(dict(seq=seq, sid=sid, label=label, cost=cost, delivery=0, poison=(seq == poison), state="active"))
return out
def check_order(done):
"""Return per-session violations: a later sequence number completed before an earlier one."""
bad = []
last = {}
for m in done:
if m["sid"] in last and m["seq"] < last[m["sid"]]:
bad.append(f'{m["sid"]}: {m["label"]} (seq {m["seq"]}) finished after a later message')
last[m["sid"]] = max(last.get(m["sid"], 0), m["seq"])
return bad
def run(title, sessions, workers=2, poison=None, max_delivery=3, slow=None, lock_duration=99, auto_renew=True,
idle_timeout=1):
msgs = stream(poison, slow)
print(f"\n=== {title}")
print(f" receivers={workers} sessions={'on' if sessions else 'off'} max_delivery={max_delivery} "
f"lock_duration={lock_duration} auto_renew={auto_renew}")
W = [dict(name=f"R{i+1}", job=None, end=0, sid=None, lock_until=0, idle=0, gen=0) for i in range(workers)]
locks = {} # session ID -> (receiver name, generation) currently holding it
done, dlq, log = [], [], []
t = 0
while any(m["state"] in ("active", "locked") for m in msgs) or any(w["job"] for w in W):
# 1) session locks that expire without renewal
for w in W:
if sessions and w["sid"] and not auto_renew and t >= w["lock_until"]:
sid = w["sid"]
log.append(f't={t:>2} {w["name"]} session lock on {sid} expired (no renewal)')
if w["job"]:
j = w["job"]
j["delivery"] += 1 # Learn: lock expiry increments delivery count
j["_stale"] = w["name"] + str(w["gen"])
if j["delivery"] >= max_delivery:
j["state"] = "dead-lettered"; dlq.append(j)
log.append(f't={t:>2} {sid} {j["label"]} reached delivery {j["delivery"]} '
f'-> dead-lettered (MaxDeliveryCountExceeded)')
else:
j["state"] = "active"
locks.pop(sid, None); w["sid"] = None
# 2) finish work
for w in W:
m = w["job"]
if m and t >= w["end"]:
token = w["name"] + str(w["gen"])
if m.get("_stale") == token:
log.append(f't={t:>2} {w["name"]} finished {m["sid"]} {m["label"]} but its lock was lost: '
f'complete fails (SessionLockLost); side effects already happened')
m.pop("_stale")
elif m["poison"]:
m["delivery"] += 1
if m["delivery"] >= max_delivery:
m["state"] = "dead-lettered"; dlq.append(m)
log.append(f't={t:>2} {w["name"]} {m["sid"]} {m["label"]} failed, delivery {m["delivery"]} '
f'-> dead-lettered; session continues')
else:
m["state"] = "active"
log.append(f't={t:>2} {w["name"]} {m["sid"]} {m["label"]} failed, abandoned '
f'(delivery {m["delivery"]}); served again next')
else:
m["state"] = "completed"; done.append(m)
log.append(f't={t:>2} {w["name"]} completed {m["sid"]} {m["label"]} (seq {m["seq"]})')
w["job"] = None; w["idle"] = t
# 3) hand out work
for w in W:
if w["job"]:
continue
avail = sorted((m for m in msgs if m["state"] == "active"), key=lambda m: m["seq"])
if not sessions:
if avail:
m = avail[0]
else:
continue
else:
if w["sid"]:
mine = [m for m in avail if m["sid"] == w["sid"]]
if not mine:
if t - w["idle"] >= idle_timeout: # sessionIdleTimeout: release and look for another
log.append(f't={t:>2} {w["name"]} released {w["sid"]} (idle)')
locks.pop(w["sid"], None); w["sid"] = None
else:
continue
else:
m = mine[0]
if not w["sid"]:
free = [m for m in avail if m["sid"] not in locks]
if not free:
continue
m = free[0]
w["sid"] = m["sid"]; w["gen"] += 1; locks[m["sid"]] = (w["name"], w["gen"])
w["lock_until"] = t + lock_duration
log.append(f't={t:>2} {w["name"]} accepted session {m["sid"]}')
m["state"] = "locked"
w["job"], w["end"] = m, t + m["cost"]
log.append(f't={t:>2} {w["name"]} started {m["sid"]} {m["label"]} (seq {m["seq"]}, delivery {m["delivery"] + 1})')
t += 1
if t > 200:
sys.exit("simulation did not finish")
for line in log:
print(" ", line)
bad = check_order(done)
gaps = [f'{m["sid"]}: {m["label"]} completed although {d["label"]} (seq {d["seq"]}) was dead-lettered'
for m in done for d in dlq if d["sid"] == m["sid"] and d["seq"] < m["seq"]]
lost = sum("lock was lost" in line for line in log)
print(f" finished at t={t - 1}; completed={len(done)} dead-lettered={len(dlq)} "
f"runs whose complete failed (work done twice or wasted)={lost}")
print(" per-session order:", "OK" if not bad else "VIOLATED")
for b in bad:
print(" -", b)
for g in gaps:
print(" gap:", g)
return dict(t=t - 1, bad=len(bad), dlq=len(dlq), done=len(done), gaps=len(gaps), lost=lost)
if __name__ == "__main__":
print("SIMULATION of documented Service Bus session behaviour. Not Service Bus. Time is in ticks.")
r = {}
r[1] = run("1. Competing consumers, no sessions", sessions=False, workers=3)
r[2] = run("2. Sessions on, three receivers", sessions=True, workers=3)
r[3] = run("3. Sessions on, order-B paid always fails (poison)", sessions=True, workers=2, poison=5)
r[4] = run("4. Sessions on, order-A created takes 6 ticks, lock 4 ticks, no renewal", sessions=True, workers=2,
slow=(1, 6), lock_duration=4, auto_renew=False)
r[5] = run("5. Same as 4, with automatic lock renewal", sessions=True, workers=2,
slow=(1, 6), lock_duration=4, auto_renew=True)
print("\nSUMMARY")
for k, v in r.items():
print(f" scenario {k}: finished t={v['t']}, completed={v['done']}, dead-lettered={v['dlq']}, "
f"order violations={v['bad']}, gaps after DLQ={v['gaps']}, failed completes={v['lost']}")Related guides
For poison messages and dead-lettering in workflows, see Logic Apps Service Bus poison messages. To choose a broker before you choose a feature, read Event Hubs vs Service Bus vs Event Grid. If your ordered messages feed Dynamics 365, D365 DMF vs OData compares the import options, including DMF’s optional in-order processing. More posts are in the Azure Integration category.
Sources
- Message sessions (Microsoft Learn)
- Message sequencing and timestamps (Microsoft Learn)
- Message transfers, locks, and settlement (Microsoft Learn)
- Enable message sessions for a queue or subscription (Microsoft Learn)
- Partitioned queues and topics (Microsoft Learn)
- Service Bus quotas and limits (Microsoft Learn)
- Service Bus Premium and Standard tiers (Microsoft Learn)
- Chaining entities with auto-forwarding (Microsoft Learn)
- Service Bus dead-letter queues (Microsoft Learn)
- Service Bus messaging exceptions (Microsoft Learn)
- Best practices for performance improvements using Service Bus messaging (Microsoft Learn)
- Authenticate a managed identity with Microsoft Entra ID to access Service Bus (Microsoft Learn)
- Monitoring data reference for Service Bus (Microsoft Learn)
- Azure Service Bus trigger for Azure Functions (Microsoft Learn)
- Azure Service Bus bindings for Azure Functions: host.json settings (Microsoft Learn)
- Send related messages in order by using a sequential convoy in Azure Logic Apps (Microsoft Learn)
- Connect to Azure Service Bus from workflows in Azure Logic Apps (Microsoft Learn)
- Sequential Convoy pattern (Azure Architecture Center)
- ServiceBusSessionProcessorOptions class (.NET API reference)
- ServiceBusSessionProcessor class (.NET API reference)
- ProcessSessionMessageEventArgs class (.NET API reference)
- Azure Service Bus client library for Python (Microsoft Learn)
- Service Bus pricing (Microsoft Azure)




