Reliable Functions and Logic Apps with messaging
Process messages idempotently with locks, retries, dead-lettering and manual replay.
By Invicly Tech, , in Microsoft Azure Cloud Engineering. About 13 minutes to read.
In short
A reliable message handler finishes the work once, even when the same message arrives twice, the process crashes, or a dependency is down. On Azure that means a Function or Logic App reading Service Bus with peek-lock, an idempotent handler, bounded retries, and a dead-letter queue that someone actually checks. When the cause is fixed, failed messages are replayed by hand.
Think of it like this: Peek-lock is like borrowing a library book: you hold it for a while, and if you do not return it in time it goes back on the shelf for someone else.
Explained simply
Messages fail. A database is busy, a bug throws an error, or a server restarts halfway through. A reliable workflow expects this. It retries what might work next time, stops retrying what never will, and never does the same piece of work twice by accident.
Service Bus helps with peek-lock. When your code receives a message, the message is hidden and locked, not deleted. If your code finishes, it completes the message and it is gone. If your code crashes or gives up, the lock runs out and the message comes back for another try.
Because messages can come back, your code may see the same one twice. Idempotent code makes this harmless. For example, before charging an order, it checks a table of order IDs it has already charged. If the ID is there, it simply stops.
After a set number of tries, ten by default, Service Bus moves the message to the dead-letter queue. That is a holding area for problem messages. A person looks at them, fixes the cause, and then sends them back to be processed again. That last step is called a replay.
Press Play on a diagram to walk through it one step at a time.
- 1Sent
Producer sends with a MessageId
- 2Locked
Function receives it in peek-lock mode
- 3Processed
Handler checks whether it already did this work
- 4Completed
Success removes the message
- 5Retried or dead-lettered
Failures return it; after MaxDeliveryCount it moves to the DLQ
- You write code in Python, C#, JavaScript and more
- Auto-completes on success, abandons on exception
- Lock renewed automatically up to a limit
- Best for custom logic and unit tests
- Designer-built workflow with connectors
- Explicit Complete and Dead-letter actions
- Retry policy on each action
- Run history and resubmit for operators
In depth
Settling a message: complete, abandon, dead-letter, defer
In peek-lock mode a receiver must settle each message. Complete removes it. Abandon releases the lock at once so it can be delivered again, and the delivery count goes up. Dead-letter moves it straight to the dead-letter queue with a reason, which is right for a message that can never succeed, such as invalid JSON. Defer sets it aside to be fetched later by sequence number. If the receiver does nothing, the lock expires after the lock duration, 1 minute by default, and the effect is like an abandon. Azure Functions settles for you: with autoCompleteMessages left at its default of true, a normal return completes the message and an exception abandons it. The Functions host also renews the lock while your code runs, up to maxAutoLockRenewalDuration, 5 minutes by default.
- Complete: done, remove it
- Abandon: try again, count goes up
- Dead-letter: never going to work, keep for review
- Lock expiry behaves like abandon
Designing an idempotent handler
Idempotent means running the handler twice gives the same result as running it once. The most dependable pattern is an inbox table. The producer sets a stable MessageId, such as the order ID. The handler opens a database transaction, inserts the MessageId into a processed_messages table with a unique constraint, does its business writes, and commits. A duplicate hits the unique constraint, so the handler rolls back and returns normally, letting the message complete. Other techniques help too: upserts instead of inserts, setting a status rather than adding to a balance, and passing an idempotency key to payment providers that support one. Service Bus duplicate detection is useful but only filters resent messages on the way in, inside a time window. It does not protect you from processing the same delivery twice after a crash.
- 1Begin transaction
- 2Insert MessageId
Unique constraint on processed_messages
- 3Duplicate?
Yes: roll back and return, message completes
- 4Do business writes
Order status, payment record
- 5Commit
Then the trigger completes the message
Retries: transient versus poison
A transient failure goes away on its own: a timeout, a throttled database, a brief network error. A poison message fails every time: bad data, a missing required field, a bug. Retry transient failures inside the handler with a short backoff, using your SDK's retry settings, so one blip does not spend a delivery attempt. Let Service Bus redeliver for failures that last longer. Note that Service Bus redelivers straight away, without a delay, so ten quick failures can burn through MaxDeliveryCount in seconds during an outage. If you need longer waits, send a copy of the message scheduled for later and complete the original. For poison messages, dead-letter them yourself as soon as you can tell, with a clear reason, rather than wasting nine more attempts.
- Transient: retry in code with backoff
- Long outage: let redelivery or a scheduled resend handle it
- Poison: dead-letter immediately with a reason
- Alert on the dead-letter count, not on each failure
Reading the dead-letter queue
Every queue and topic subscription has a dead-letter subqueue, addressed as orders/$deadletterqueue. Messages there keep their body and properties, plus DeadLetterReason and DeadLetterErrorDescription. Common reasons are MaxDeliveryCountExceeded, TTLExpiredException when expiry dead-lettering is turned on, and whatever reason your own code set. Service Bus never cleans this queue for you, and messages there count toward the namespace size. You can browse it in the portal with Service Bus Explorer, check the count with az servicebus queue show and countDetails.deadLetterMessageCount, or read it with an SDK. Treat a growing count as an incident signal and create an Azure Monitor alert on the DeadletteredMessages metric.
Logic Apps and manual replay
Logic Apps is a low-code alternative to a Function. A workflow can start with the Service Bus trigger that receives messages in peek-lock mode, call other connectors, and then use the Complete or Dead-letter actions. Each action has a retry policy; the default is exponential backoff with up to four retries. Run history shows every input and output, and you can resubmit a failed run once the cause is fixed. Replay from the dead-letter queue is a manual decision. Read each dead-lettered message, fix the data or deploy the bug fix, send a copy back to the main queue, and complete the dead-lettered original. Keep the same MessageId so your inbox table still blocks duplicates. If duplicate detection is on, wait until its window has passed, or the resend will be silently dropped.
- 1Alert fires
Dead-letter count above zero
- 2Inspect
Read reason and a sample body
- 3Fix cause
Deploy code fix or correct data
- 4Replay
Resend copies, complete originals
- 5Verify
Main queue drains, DLQ back to zero
- Back to step 1
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Trigger a Function from Service Bus~35m
- 2Make handlers idempotent~35m
- 3Handle lock renewal and retries~35m
- 4Inspect the dead-letter queue~35m
- 5Replay a message by hand~35m
Key points
- Peek-lock hides a message for the lock duration; it reappears if not settled.
- Every failed attempt raises the delivery count; at the limit (10 by default) it is dead-lettered.
- Idempotency means repeating a message has the same effect as running it once.
- The dead-letter queue is a subqueue that never empties by itself; alert on its count.
- Replay only after the root cause is fixed, and keep the original MessageId.
Key terms
Tap a card to flip it. 0/5 known
Examples
import azure.functions as func
app = func.FunctionApp()
@app.service_bus_queue_trigger(arg_name="msg", queue_name="orders",
connection="ServiceBusConnection")
def handle_order(msg: func.ServiceBusMessage) -> None:
order_id = msg.message_id
if already_processed(order_id): # look up in your database
return # duplicate: do nothing, let it complete
charge_and_record(order_id, msg.get_body()) # one transaction
# raising an exception abandons the message so Service Bus retries itPython v2 programming model. The helper functions stand for your own data access code.
A synthetic poison message end to end
Prerequisites: a Standard namespace with an orders queue created with --max-delivery-count 3 so the lab is quick, and the Function below, whose managed identity has the Azure Service Bus Data Receiver role. Step 1: send a good fixture, {"orderId": "ord-1001", "amount": 25.00}, with MessageId ord-1001. Evidence: one execution in the Function log and an active count of 0. Step 2: send it again with the same MessageId. Evidence: the log says already processed and nothing else changes. Step 3: send a poison fixture, {"orderId": "ord-1002", "amount": "abc"}. The handler raises, Service Bus redelivers it three times, then dead-letters it with MaxDeliveryCountExceeded. Evidence: deadLetterMessageCount is 1. Cleanup: delete the resource group.
import json, logging
import azure.functions as func
app = func.FunctionApp()
@app.service_bus_queue_trigger(arg_name="msg", queue_name="orders",
connection="ServiceBusConnection")
def handle(msg: func.ServiceBusMessage) -> None:
order = json.loads(msg.get_body())
if not isinstance(order.get("amount"), (int, float)):
raise ValueError(f"invalid amount in {msg.message_id}") # abandons
if already_processed(msg.message_id):
logging.info("already processed %s", msg.message_id)
return
record_order(msg.message_id, order) # inbox insert + order in one transactionReplaying dead-lettered orders after a fix
A bug rejected every order with a currency of CHF, and 37 messages are in the dead-letter queue. Step 1: browse a few in Service Bus Explorer and confirm they share the same DeadLetterErrorDescription. Step 2: deploy the fix and test it with one new message. Step 3: run the script below, which reads each dead-lettered message, sends a copy to the main queue with the same MessageId and properties, and completes the original. The identity needs Data Sender and Data Receiver roles on the namespace. Step 4: evidence: the dead-letter count falls to 0, the main queue drains, and 37 orders show as processed. Rollback: if the fix is wrong, the messages return to the dead-letter queue and nothing is lost.
from azure.identity import DefaultAzureCredential
from azure.servicebus import ServiceBusClient, ServiceBusMessage, ServiceBusSubQueue
NS = "sb-contoso-lab.servicebus.windows.net"
with ServiceBusClient(NS, DefaultAzureCredential()) as client:
dlq = client.get_queue_receiver("orders", sub_queue=ServiceBusSubQueue.DEAD_LETTER,
max_wait_time=5)
sender = client.get_queue_sender("orders")
with dlq, sender:
for m in dlq:
sender.send_messages(ServiceBusMessage(b"".join(m.body),
message_id=m.message_id, application_properties=m.application_properties))
dlq.complete_message(m)Quick reference
- Lock duration default 1 minute, maximum 5 minutes; Functions auto-renews up to 5 minutes by default
- MaxDeliveryCount default 10; reaching it dead-letters with MaxDeliveryCountExceeded
- Dead-letter path: queue/$deadletterqueue or topic/subscriptions/name/$deadletterqueue
- Functions: return completes, exception abandons (autoCompleteMessages = true)
- Idempotency: unique MessageId in an inbox table, written in the same transaction as the work
- Dead-letter poison messages yourself with a clear reason instead of waiting for 10 failures
- Alert on the DeadletteredMessages metric; the DLQ never empties itself
- Replay keeps the MessageId; wait out the duplicate detection window if it is on
Common mistakes
- Writing to the database and then failing before completion, without a duplicate check, so the retry charges twice.
- Letting work run longer than the lock (and the Functions auto-renew limit) so another instance receives the same message.
- Nobody watching the dead-letter count, so failed orders sit there for weeks.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Check how many active and dead-lettered messages a queue holds, using the CLI.
- Exercise 2medium
Write the SQL for an inbox table and the statement a handler runs first, so a second delivery of the same message is detected.
- Exercise 3hard
During a 20-minute database outage every order failed and was dead-lettered within seconds. Propose two changes so the next outage does not fill the dead-letter queue, and describe the replay for this one.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why did my message get processed twice?
- Most often the handler ran longer than the lock, or crashed after doing the work but before completing. The lock expired and Service Bus delivered it again. Make the handler idempotent and keep work shorter than the lock renewal limit.
- Does the dead-letter queue delete old messages?
- No. Messages stay there until something receives and completes them, so you need an alert and a triage routine.
- Should I use receive-and-delete mode to keep things simple?
- Only when losing a message is acceptable. Receive-and-delete removes the message as soon as it is handed over, so a crash loses it for good.
- Can I replay messages from the Azure portal?
- Service Bus Explorer lets you browse and act on dead-lettered messages, and depending on the current portal version it can resend them. For bulk or audited replays a small SDK script is easier to review and repeat.