Skip to main content

Ordering Messages In An Amazon SQS Queue

Last November, AWS released a very useful feature in its FIFO support for Amazon Simple Queue Service (SQS). FIFO stands for “first in first out”, which essentially means that a FIFO queue maintains the order of how messages are delivered out of an SQS queue. The FIFO queue feature also guarantees on-time delivery of a message, which is a pretty big deal if you’ve had to design systems where on-time delivery was a “must have” feature.

Prior to having FIFO queue support for SQS, the random order of SQS messages was not a deal breaker but any ordering needed to be handled outside of SQS. You could create your own ordering key and parse it in the message attributes. Features such as the message timeout window and dead letter queues helped manage the issue of message duplication if needed. This approach didn’t always suit if you needed to implement a queue where the order and frequency of messages were mission critical.

Enter First In First Out queue support for Amazon SQS in US West and US East.

How FIFO for Amazon SQS works

You interact with a FIFO SQS queue the same way that you interact with a standard SQS queue. With a FIFO queue, however, the order in which messages are sent and received is strictly preserved. A message is delivered once and remains available until a consumer processes and deletes it. This means that duplicates will not be created in the queue. This is pretty cool, so let’s take a look at how we can use it.

An SQS queue is recognized as a FIFO queue if it has the FifoQueue attribute set to true and the queue name ends with the .fifo suffix. FIFO queues use the same API actions as standard queues.

// A FIFO queue must have the FifoQueue attribute set to True
attributes.put("FifoQueue", "true");
// A FIFO queue name must end with the .fifo suffix
CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyFifoQueue.fifo").withAttributes(attributes);
String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

The methods for receiving messages, deleting messages, and changing the visibility timeout are the same as for a standard SQS queue. However, when you send a message from a FIFO queue you must specify a message group ID.
Every message sent to a FIFO queue requires a MessageGroupId value. If you don’t add a MessageGroupId value, the send action fails.

// You must provide a MessageGroupId
sendMessageRequest.setMessageGroupId("1");

How Amazon SQS uses MessageGroupId

Amazon SQS uses the MessageGroupId value to group messages together. Messages within a group are ordered within that group. So if we add a MessageGroupId=1 value to 10 messages, those 10 messages are treated as a message group and will be processed one by one, in a strict order relative to the group MessageGroupId=1. If we send another five messages with a new MessageGroupId=2, those five messages will be ordered within the group MessageGroupId=2.

That means we can have multiple ordered message groups within a single queue. So, our 10 messages in MessageGroupId=1 and our five messages in MessageGroupId=2 will be processed in order relative to each group rather than to the queue as a whole. As ordering only applies to the message group, messages that belong to a different message group might be processed in the same order.

If you have a system that will have multiple senders and multiple recipients, you should generate a unique MessageGroupId for each message. If you don’t need to create multiple ordered message groups, just use the same MessageGroupId for all of your messages.

If your SendMessage action fails, you can retry sending as many times as you want using the same message deduplication ID. Assuming that you receive at least one acknowledgment before the deduplication interval expires (the minimum deduplication window is five minutes), multiple retries will not affect the ordering of messages or create duplications.

When you receive messages, SQS will try to return as many messages with the same MessageGroupId as possible. However, you can’t request to receive messages with a specific MessageGroupId. If you get a failed ReceiveMessage action, you can retry using the same receive request attempt ID. Assuming that you receive at least one acknowledgment before the visibility timeout expires, multiple retries will not affect the ordering of messages.

A FIFO message uses a MessageDeduplicationId key to manage deduplication of sent messages. Every message must have a unique MessageDeduplicationId. If a message with a particular MessageDeduplicationId is sent successfully, any messages sent with the same MessageDeduplicationId will not be delivered during the five-minute deduplication window.

So, if you send 10 messages in succession to a FIFO queue, each with a distinct MessageDeduplicationId, SQS acknowledges the transmission and stores those messages. Then, each message can be received and processed in the exact order in which the messages were transmitted.

How to create a MessageDeduplicationId

There are two ways to create a MessageDeduplicationId. First, you can define your own MessageDeduplicationId for the message. If your application sends messages with identical message bodies, you can modify your code to provide a unique message MessageDeduplicationId for each sent message.

// define a MessageDeduplicationId
sendMessageRequest.setMessageDeduplicationId("1");

Second, you can just enable content-based deduplication. This tells SQS to use an SHA-256 hash to generate the MessageDeduplicationId using the body of the message. If your application sends messages with unique message bodies, then enabling content-based deduplication will be easiest.

// Generate a MessageDeduplicationId based on the content
attributes.put("ContentBasedDeduplication", "true");

Is a FIFO SQS for you?

Here are five things to keep in mind when considering if a FIFO SQS queue suits your use case.

1. Conversions. You can’t convert an existing standard queue into a FIFO queue. You need to delete your standard queue and then create a new FIFO queue.
2. Transaction rate. FIFO queues are limited to 300 transactions per second (TPS). If your application needs a higher rate than 300 TPS, stick to a standard SQS queue.
3. Delays. FIFO queues support per queue delays but not per message delays. If your application sets a DelaySeconds = 10 on each message, that’s probably not going to work with a FIFO queue. You will need to remove any per message parameter and set a DelaySeconds =10 parameter on the entire queue.
4. Processing time. You need to ensure that there is enough time to process and delete a message. Extend your message visibility timeout to the maximum time it takes to process and delete the message. If you don’t know how long it takes to process a message, specify the initial visibility timeout plus the period of time after which you can check whether the message is processed. If it’s taking a long time to process messages and your visibility timeout is already set to a high value, consider adding a receive request attempt ID to each ReceiveMessage action. This allows you to retry receive attempts in case of network failures and prevents queues from pausing due to failed receive attempts.
5. Inflight message limit. While Amazon SQS queues can include an unlimited number of messages, there is a 20,000 inflight message limit for inflight FIFO queues (The inflight message limit for standard SQS queues is 120,000.). Messages are inflight after they have been received from the queue by a consumer, but have not yet been deleted from the queue.

Learning more about FIFO SQS

Hopefully, I have piqued your interest in this great new feature. There is a lot more to know about SQS FIFO, so if you are interested, I suggest starting with the AWS developer guide and API reference. If you have any questions or content you’d like to add, please leave a comment right here below this post.

Avatar

Written by

Andrew Larkin

Andrew is an AWS certified professional who is passionate about helping others learn how to use and gain benefit from AWS technologies. Andrew has worked for AWS and for AWS technology partners Ooyala and Adobe. His favorite Amazon leadership principle is "Customer Obsession" as everything AWS starts with the customer. Passions around work are cycling and surfing, and having a laugh about the lessons learnt trying to launch two daughters and a few start ups.

Related Posts

Avatar
John Chell
— June 13, 2019

AWS Certified Solutions Architect Associate: A Study Guide

The AWS Solutions Architect - Associate Certification (or Sol Arch Associate for short) offers some clear benefits: Increases marketability to employers Provides solid credentials in a growing industry (with projected growth of as much as 70 percent in five years) Market anal...

Read more
  • AWS
  • AWS Certifications
Chris Gambino and Joe Niemiec
Chris Gambino and Joe Niemiec
— June 11, 2019

Moving Data to S3 with Apache NiFi

Moving data to the cloud is one of the cornerstones of any cloud migration. Apache NiFi is an open source tool that enables you to easily move and process data using a graphical user interface (GUI).  In this blog post, we will examine a simple way to move data to the cloud using NiFi c...

Read more
  • AWS
  • S3
Avatar
Chandan Patra
— June 11, 2019

Amazon DynamoDB: 10 Things You Should Know

Amazon DynamoDB is a managed NoSQL service with strong consistency and predictable performance that shields users from the complexities of manual setup.Whether or not you've actually used a NoSQL data store yourself, it's probably a good idea to make sure you fully understand the key ...

Read more
  • AWS
  • DynamoDB
Avatar
Andrew Larkin
— June 6, 2019

The 11 AWS Certifications: Which is Right for You and Your Team?

As companies increasingly shift workloads to the public cloud, cloud computing has moved from a nice-to-have to a core competency in the enterprise. This shift requires a new set of skills to design, deploy, and manage applications in cloud computing.As the market leader and most ma...

Read more
  • AWS
  • AWS Certifications
Sam Ghardashem
Sam Ghardashem
— May 15, 2019

Aviatrix Integration of a NextGen Firewall in AWS Transit Gateway

Learn how Aviatrix’s intelligent orchestration and control eliminates unwanted tradeoffs encountered when deploying Palo Alto Networks VM-Series Firewalls with AWS Transit Gateway.Deploying any next generation firewall in a public cloud environment is challenging, not because of the f...

Read more
  • AWS
Joe Nemer
Joe Nemer
— May 3, 2019

AWS Config Best Practices for Compliance

Use AWS Config the Right Way for Successful ComplianceIt’s well-known that AWS Config is a powerful service for monitoring all changes across your resources. As AWS Config has constantly evolved and improved over the years, it has transformed into a true powerhouse for monitoring your...

Read more
  • AWS
  • Compliance
Avatar
Francesca Vigliani
— April 30, 2019

Cloud Academy is Coming to the AWS Summits in Atlanta, London, and Chicago

Cloud Academy is a proud sponsor of the 2019 AWS Summits in Atlanta, London, and Chicago. We hope you plan to attend these free events that bring the cloud computing community together to connect, collaborate, and learn about AWS. These events are all about learning. You can learn how t...

Read more
  • AWS
  • AWS Summits
Paul Hortop
Paul Hortop
— April 2, 2019

How to Monitor Your AWS Infrastructure

The AWS cloud platform has made it easier than ever to be flexible, efficient, and cost-effective. However, monitoring your AWS infrastructure is the key to getting all of these benefits. Realizing these benefits requires that you follow AWS best practices which constantly change as AWS...

Read more
  • AWS
  • Monitoring
Joe Nemer
Joe Nemer
— April 1, 2019

AWS EC2 Instance Types Explained

Amazon Web Services’ resource offerings are constantly changing, and staying on top of their evolution can be a challenge. Elastic Cloud Compute (EC2) instances are one of their core resource offerings, and they form the backbone of most cloud deployments. EC2 instances provide you with...

Read more
  • AWS
  • EC2
Avatar
Nitheesh Poojary
— March 26, 2019

How DNS Works – the Domain Name System (Part One)

Before migrating domains to Amazon's Route53, we should first make sure we properly understand how DNS worksWhile we'll get to AWS's Route53 Domain Name System (DNS) service in the second part of this series, I thought it would be helpful to first make sure that we properly understand...

Read more
  • AWS
Avatar
Stuart Scott
— March 14, 2019

Multiple AWS Account Management using AWS Organizations

As businesses expand their footprint on AWS and utilize more services to build and deploy their applications, it becomes apparent that multiple AWS accounts are required to manage the environment and infrastructure.  A multi-account strategy is beneficial for a number of reasons as ...

Read more
  • AWS
  • Identity Access Management
Avatar
Sanket Dangi
— February 11, 2019

WaitCondition Controls the Pace of AWS CloudFormation Templates

AWS's WaitCondition can be used with CloudFormation templates to ensure required resources are running.As you may already be aware, AWS CloudFormation is used for infrastructure automation by allowing you to write JSON templates to automatically install, configure, and bootstrap your ...

Read more
  • AWS
  • CloudFormation