Azure Service Bus Messages – Structure, Properties & Type

In our previous article, Introduction to Azure Service Bus, we explored the fundamentals of Azure Service Bus, including its architecture, queues, topics, subscriptions, and messaging patterns.

Messages are the core building blocks of Azure Service Bus. They enable different applications and services to communicate asynchronously without requiring direct interaction between them.

An Azure Service Bus message contains a payload (the actual data being transferred) along with metadata that provides additional information about the message. This metadata includes system-defined properties and custom application properties that help identify, manage, route, and process messages.

azure message bus, Azure Service Bus message structure showing message body, system properties, and application properties

Azure Service Bus also provides various message handling capabilities, such as scheduling messages for future delivery, deferring message processing, and moving failed messages to a Dead-Letter Queue.

In our previous article, Introduction to Azure Service Bus – Messaging, Queues and Topics, we explored the fundamentals of Azure Service Bus, including its architecture, queues, topics, subscriptions, and messaging patterns.

In this article, we will explore the structure of Azure Service Bus messages, understand their important properties, examine different message handling scenarios, and learn about the operations involved in sending and receiving messages using C#.

Understanding Azure Service Bus Message Structure

An Azure Service Bus message consists of three main components:
  • Message Body: Contains the actual data or payload that needs to be transferred between applications or services.
  • System Properties: Contains predefined metadata maintained by Azure Service Bus or provided through the message API to identify, manage, and control message processing.
  • Application Properties: Contains custom key-value pairs defined by the application to store additional metadata and business-related information.

These components help applications exchange data asynchronously while maintaining the information required for message identification, routing, and processing.

Example:

Consider an Order Management application that publishes an order creation message to an Azure Service Bus queue.

The message might contain:
  • Message Body: Contains order details such as OrderId, CustomerId, Items, and TotalAmount.
  • System Properties: Contains MessageId to uniquely identify the message and CorrelationId to associate it with a related workflow.
  • Application Properties: Contains OrderType, Priority, and PaymentStatus to provide additional business context.

By separating the actual payload from its metadata, Azure Service Bus makes it easier for distributed applications to exchange and process messages efficiently.

Understanding Message Body

The Message Body contains the actual data or payload that a sender wants to transfer to a receiver through Azure Service Bus.

Unlike System Properties and Application Properties, which contain metadata, the message body holds the business data required by the receiving application.

Azure Service Bus supports transferring both text-based and binary payloads. The message body is represented by the BinaryData type in the Azure.Messaging.ServiceBus SDK.

Let's understand the different ways of working with message bodies.

JSON Payload

JSON (JavaScript Object Notation) is one of the most commonly used formats for exchanging data between applications and services.

In distributed applications, the sender can serialize a business object into JSON and place it inside the Azure Service Bus message body. The receiver can then deserialize the JSON payload back into the corresponding object.

Example:

Consider an Order Management application that needs to send order details to another service. The order data can be represented using the following JSON payload:

</> JSON
{
  "OrderId": 101,
  "CustomerId": 501,
  "Items": [
    {
      "ItemName": "Pizza",
      "Quantity": 2,
      "Price": 250
    }
  ],
  "TotalAmount": 500
}

The sender serializes the order object into JSON and sends it through Azure Service Bus. The receiving application reads the message body and deserializes the JSON into an Order object for further processing.

Binary Data

Azure Service Bus also supports transferring binary data through the message body. Binary data represents information in its raw byte format rather than a human-readable text format.

For example:
  • Images
  • Compressed files
  • Serialized objects
  • Protocol Buffers (Protobuf) payloads

The sender converts the data into a byte array and uses it to create an Azure Service Bus message. The receiver retrieves the message body as binary data and converts it back into the required format.

Example:

Consider a document processing application that needs to transfer a PDF document between two services.

The sender reads the PDF file as bytes and sends it through Azure Service Bus. The receiving application retrieves the binary payload and saves it as a PDF document.

Understanding Message Properties in Azure Service Bus

In Azure Service Bus, message properties are metadata associated with a message that provide additional information beyond the actual message body.

These properties help applications identify messages, correlate related workflows, control message delivery, and implement message filtering and routing.

Azure Service Bus message properties are broadly classified into two categories:
  1. System Properties: Predefined properties provided through the Azure Service Bus messaging API, such as MessageId, CorrelationId, ContentType, and SessionId.
  2. Application Properties: Custom key-value pairs defined by developers to store business-specific information, such as OrderType, Priority, PaymentStatus, and CustomerId.

Both types of properties work together to help distributed applications exchange, identify, and process messages efficiently.

Understanding System Properties in Azure Service Bus

System Properties are predefined properties associated with an Azure Service Bus message. They provide additional information about the message and help applications manage message identification, correlation, routing, scheduling, and processing.

System Properties are provided through the Azure Service Bus messaging API. Some properties are set by the sender, while others are populated or maintained by Azure Service Bus during message processing.

Let's explore some of the important System Properties.
  1. MessageId: MessageId is used to uniquely identify a message within an application or messaging workflow. It is generally assigned by the sender and can be used for message tracking, duplicate detection, and troubleshooting.
  2. CorrelationId: CorrelationId is used to associate a message with another message or a related business workflow. It is particularly useful in distributed applications where multiple services participate in processing a single business transaction.
  3. ContentType: ContentType specifies the format or type of data stored in the message body. It helps the receiving application understand how to interpret the message payload. Common examples include application/json, application/xml, and text/plain.
  4. Subject: Subject describes the purpose or type of the message. It can be used to identify the business event or operation represented by the message, such as OrderCreated, PaymentCompleted, or OrderCancelled.
  5. SessionId: SessionId is used to group related messages into a logical session. It enables session-based processing and helps maintain message ordering within a session. It is particularly useful when processing multiple messages belonging to the same order or customer workflow.
  6. TimeToLive (TTL): TimeToLive specifies how long a message can remain valid in a queue or subscription. Once the message expires, it is no longer available for normal delivery. Depending on the entity configuration, expired messages can be moved to the Dead-Letter Queue or discarded.
  7. ReplyTo: ReplyTo specifies the destination where the receiving application should send a response. It is useful when implementing request-response communication patterns using Azure Service Bus.
  8. ReplyToSessionId: ReplyToSessionId specifies the session identifier that should be used when sending a response to the destination specified by ReplyTo. It is useful in request-response scenarios that involve session-based messaging.
  9. To: To specifies the intended destination of a message. It can be used by applications to identify the logical recipient of a message.
  10. ScheduledEnqueueTime: ScheduledEnqueueTime specifies the date and time when a message should become available for delivery. It is useful when an application needs to schedule message processing for a future time.
  11. DeliveryCount: DeliveryCount indicates how many times a message has been delivered to a receiver. It is useful for identifying messages that repeatedly fail during processing and troubleshooting message delivery issues.
  12. EnqueuedTime: EnqueuedTime indicates the date and time when a message was accepted and stored by Azure Service Bus. It helps applications monitor message age and identify processing delays.
  13. SequenceNumber: SequenceNumber is a unique, service-assigned number that identifies a message within its queue or subscription. It is useful for tracking messages and managing deferred message processing.
  14. PartitionKey: PartitionKey is used to group related messages into the same partition when partitioning is enabled. It helps maintain related message handling within a partition and is particularly useful in partitioned messaging scenarios.
  15. DeadLetterSource: DeadLetterSource identifies the name of the entity from which a message was dead-lettered, such as a queue or subscription. It is populated by Azure Service Bus and is useful for investigating dead-lettered messages.

Understanding Application Properties in Azure Service Bus

Application Properties are custom key-value pairs defined by developers to store additional metadata or business-specific information associated with an Azure Service Bus message.

Unlike System Properties, which are predefined by Azure Service Bus, Application Properties allow developers to define their own properties based on application requirements.

These properties are stored separately from the message body and can be accessed by the receiving application without deserializing the entire message payload.

Application Properties are particularly useful for message identification, filtering, routing, and implementing business-specific processing logic.

Example

Consider an Order Management application that publishes order messages to an Azure Service Bus Topic. The message body contains the actual order details, while Application Properties provide additional business context.

For example:
  • OrderType: Identifies the type of order, such as DineIn, Takeaway, or Delivery.
  • Priority: Indicates the processing priority, such as High, Medium, or Low.
  • PaymentStatus: Indicates the payment status, such as Paid, Pending, or Failed.
  • CustomerId: Identifies the customer associated with the order.

These properties allow receiving applications to understand the business context of a message without inspecting its entire payload.

Implementation

Application Properties can be defined using the ApplicationProperties collection available in the ServiceBusMessage class.

</> C#
var message = new ServiceBusMessage(
BinaryData.FromObjectAsJson(order));
// Define Application Properties
message.ApplicationProperties["OrderType"] = "Delivery";
message.ApplicationProperties["Priority"] = "High";
message.ApplicationProperties["PaymentStatus"] = "Paid";
message.ApplicationProperties["CustomerId"] = 501;

Types of Messages in Azure Service Bus

Azure Service Bus supports different message-handling capabilities to address various communication and processing requirements in distributed applications.

Depending on how messages are created, scheduled, processed, or handled when failures occur, we commonly encounter the following message types and scenarios:

Standard Message

A Standard Message is a regular message sent by a producer to an Azure Service Bus queue or topic for processing by one or more consumers.

It contains a message body along with System Properties and optional Application Properties.

Example: An Order Management application publishes an order creation message to a queue. An Order Processing Service receives the message and processes the order.

Scheduled Message

A Scheduled Message is a message configured to become available for delivery at a specific future date and time.

Azure Service Bus stores the scheduled message and makes it available for consumers when the scheduled delivery time arrives.

Example: An e-commerce application schedules an order reminder message to be delivered to a customer after 24 hours.

Deferred Message

A Deferred Message is a message that a consumer intentionally postpones processing.

Instead of completing or abandoning the message, the consumer defers it. The message remains in the queue or subscription but is excluded from normal message retrieval.

The consumer can retrieve the deferred message later using its SequenceNumber.

Example: An Order Processing Service receives an order message but cannot process it because the required customer information is not yet available. It defers the message and retrieves it later when the required information becomes available.

Dead-Letter Message

A Dead-Letter Message is a message moved to the Dead-Letter Queue (DLQ) because it cannot be processed successfully or meets a dead-lettering condition.

Messages can be moved to the DLQ due to repeated delivery failures, message expiration (depending on entity configuration), or explicit dead-lettering by an application.

The Dead-Letter Queue allows developers to investigate failed messages, identify processing issues, and take corrective actions.

Example: An Order Processing Service repeatedly fails to process an order because the message contains invalid data. After exceeding the configured maximum delivery count, Azure Service Bus moves the message to the Dead-Letter Queue.

Message Size and Payload Considerations in Azure Service Bus

Message size is an important consideration when designing applications that communicate through Azure Service Bus. Every message contains a payload (message body) along with system and application properties. The combined message size must comply with the limits supported by the selected Service Bus tier and protocol.

If a message exceeds the supported size limit, the send operation can fail. Therefore, developers should consider message size when designing message contracts and deciding what data to send.

1. Azure Service Bus Message Size Limits

Azure Service Bus supports different message size limits depending on the pricing tier and protocol.

For commonly used AMQP-based messaging:

Tier Maximum Message Size
Basic 256 KB
Standard 256 KB
Premium 100 MB

Note: Premium's larger message-size capability is supported through AMQP. HTTP and other protocol paths may have different limits. Always check the limits for the protocol and SDK operation used by your application.

2. What Contributes to Message Size?

The size of a Service Bus message is not determined only by its body. Message metadata and properties also contribute to the overall message size.

The main components include:

  1. Message Body: Contains the actual business payload, such as JSON, XML, text, or binary data.
  2. System Properties: Include metadata such as MessageId, CorrelationId, ContentType, and other message-related information.
  3. Application Properties: Custom key-value pairs added by the application, such as OrderType, Priority, and CustomerId.

For example, a message containing a large JSON document and several custom application properties may consume more space than the JSON body alone.

3. Handling Large Message Payloads

Sending large files or complex payloads directly through Azure Service Bus is generally not recommended.

Instead, a common approach is to store the actual file or large payload in Azure Blob Storage and send its reference through Service Bus.

For example, consider an application that processes customer documents.

Instead of sending the entire PDF file as a Service Bus message:

  • Upload the PDF file to Azure Blob Storage.
  • Generate a reference to the stored document.
  • Send a Service Bus message containing the document reference and relevant metadata.
  • The consumer retrieves the document from Blob Storage using the reference.

Example message payload:

</> JSON
	{
  "DocumentId": "DOC-1001",
  "FileName": "CustomerAgreement.pdf",
  "BlobUrl": "https://storageaccount.blob.core.windows.net/documents/DOC-1001.pdf",
  "DocumentType": "Agreement"
}

This approach keeps Service Bus messages small and makes large-file processing more efficient.

4. Best Practices for Message Size and Payload

Consider the following practices when designing Azure Service Bus messages:

  1. Keep messages small: Send only the information required by the consumer.
  2. Use Blob Storage for large files: Store documents, images, videos, and other large payloads in Azure Blob Storage and send references through Service Bus.
  3. Avoid unnecessary properties: Include only relevant system and application properties.
  4. Use efficient serialization: Choose an appropriate serialization format, such as JSON or a compact binary format, based on application requirements.
  5. Avoid sending duplicate data: Send identifiers or references when consumers can retrieve the required information from another data source.
  6. Validate message size: Ensure that messages remain within the supported limits before sending them.
  7. Consider security: Avoid placing sensitive information or long-lived storage access credentials directly in message properties or payloads.

Summary

Understanding the message structure and properties of Azure Service Bus is essential for building reliable and scalable distributed applications.

Azure Service Bus provides a flexible messaging model that allows applications to exchange information using message bodies, system properties, and application properties. Different message-handling capabilities, such as Standard, Scheduled, Deferred, and Dead-Letter messages, help developers address various business and processing requirements.

Choosing the appropriate receive mode, such as PeekLock or ReceiveAndDelete, is equally important because it determines how messages are acknowledged, delivered, and handled when processing failures occur.

Developers should also consider message size, payload optimization, and serialization formats when designing messaging solutions. For large files and complex payloads, integrating Azure Blob Storage with Service Bus helps improve scalability and keeps messages lightweight.

By understanding these concepts and following the recommended practices, developers can design reliable, efficient, and maintainable messaging solutions using Azure Service Bus.

Thanks

Kailash Chandra Behera

I am an IT professional with over 12 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

نموذج الاتصال