You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Azure Service Bus is a fully managed enterprise message broker that provides reliable cloud messaging as a service (MaaS) and simple hybrid integration. It supports both queue-based point-to-point messaging and publish-subscribe patterns through topics and subscriptions.
Service Bus is designed for enterprise applications requiring high reliability, ordered delivery, and transactional support. It's a core component of Azure Integration Services, enabling asynchronous and decoupled communication between applications.
The Dead-Letter Queue is a secondary sub-queue that holds messages which cannot be delivered or processed successfully. Every queue and topic subscription has an associated DLQ that is automatically created and managed by Service Bus.
Application code calls DeadLetterAsync() when business logic determines a message cannot be processed
Dead-Letter Reason Codes
Reason
Description
MaxDeliveryCountExceeded
Too many delivery attempts failed
TTLExpiredException
Message time-to-live expired
HeaderSizeExceeded
Message headers too large
SessionIdIsMissing
Session-enabled queue received non-session message
Accessing the Dead-Letter Queue
The DLQ path follows the format: <queue-name>/$deadletterqueue or <topic>/<subscription>/$deadletterqueue
// Create a receiver for the dead-letter queuevardlqPath=ServiceBusReceiverClient.FormatDeadLetterPath(queueName);vardlqReceiver=client.CreateReceiver(dlqPath);// Receive dead-lettered messagesvarmessages=awaitdlqReceiver.ReceiveMessagesAsync(maxMessages:10);foreach(varmessageinmessages){// Inspect dead-letter reasonvarreason=message.DeadLetterReason;vardescription=message.DeadLetterErrorDescription;Console.WriteLine($"DLQ Reason: {reason}, Description: {description}");// Process or resubmit the messageawaitdlqReceiver.CompleteMessageAsync(message);}
Explicitly Dead-Lettering Messages
// Dead-letter a message with custom reasonawaitreceiver.DeadLetterMessageAsync(message,deadLetterReason:"InvalidPayload",deadLetterErrorDescription:"Message format was invalid - missing required fields");
Best Practices for DLQ Management
Monitor DLQ regularly - Set up alerts for messages in DLQ
Implement DLQ processors - Create background jobs to handle dead-lettered messages
Log dead-letter reasons - Track patterns to fix root causes
Set appropriate MaxDeliveryCount - Balance between retry attempts and quick failure detection
Consider automatic cleanup - Set TTL on DLQ messages to prevent unlimited growth
// Schedule a message for future deliveryvarmessage=newServiceBusMessage("Scheduled content");varscheduledTime=DateTimeOffset.UtcNow.AddHours(1);longsequenceNumber=awaitsender.ScheduleMessageAsync(message,scheduledTime);// Cancel if neededawaitsender.CancelScheduledMessageAsync(sequenceNumber);
-- Filter by custom property
Priority >5-- Filter by system propertysys.Label='Important'-- Complex filter
Priority >3AND Region ='US'AND Amount >1000-- NULL check
OrderType IS NOT NULL
flowchart TB
PUB[Publisher] --> T[Topic]
T --> S1[Subscription: Email]
T --> S2[Subscription: SMS]
T --> S3[Subscription: Audit]
S1 --> EMAIL[Email Service]
S2 --> SMS[SMS Service]
S3 --> LOG[Log Storage]
style T fill:#50E6FF
Loading
Code Examples
Sending Messages (C#)
usingAzure.Messaging.ServiceBus;awaitusingvarclient=newServiceBusClient(connectionString);awaitusingvarsender=client.CreateSender("my-queue");// Send single messagevarmessage=newServiceBusMessage("Hello, Service Bus!");message.ApplicationProperties["Priority"]="High";awaitsender.SendMessageAsync(message);// Send batchvarbatch=awaitsender.CreateMessageBatchAsync();batch.TryAddMessage(newServiceBusMessage("Message 1"));batch.TryAddMessage(newServiceBusMessage("Message 2"));awaitsender.SendMessagesAsync(batch);
Receiving Messages (C#)
awaitusingvarclient=newServiceBusClient(connectionString);awaitusingvarprocessor=client.CreateProcessor("my-queue",newServiceBusProcessorOptions());processor.ProcessMessageAsync+=async args =>{varbody=args.Message.Body.ToString();Console.WriteLine($"Received: {body}");// Complete the messageawaitargs.CompleteMessageAsync(args.Message);};processor.ProcessErrorAsync+= args =>{Console.WriteLine($"Error: {args.Exception}");returnTask.CompletedTask;};awaitprocessor.StartProcessingAsync();
Best Practices
Design
Practice
Description
Use sessions for FIFO
When order matters
Enable duplicate detection
For at-most-once delivery
Set appropriate TTL
Prevent queue buildup
Use correlation IDs
For request tracking
Design for idempotency
Handle redelivery
Performance
Practice
Description
Use batching
Group sends/receives
Use prefetch
Reduce round trips
Choose Premium
For consistent latency
Use AMQP
Better throughput than HTTP
Connection pooling
Reuse clients
Operations
Practice
Description
Monitor DLQ
Alert on dead letters
Set up alerts
Track queue depth
Use Geo-DR
For disaster recovery
Auto-forward
Simplify routing
Monitoring
Key Metrics
Metric
Description
Alert Threshold
Active Messages
Pending messages
Based on capacity
Dead-lettered Messages
Failed messages
> 0
Incoming Messages
Rate of arrival
Baseline
Outgoing Messages
Rate of processing
Baseline
Server Errors
Backend failures
> 0
flowchart LR
SB[Service Bus] --> AM[Azure Monitor]
AM --> LA[Log Analytics]
AM --> ALERT[Alerts]
AM --> DASH[Dashboard]
style SB fill:#0078D4,color:#fff
style AM fill:#50E6FF