Amazon SQS in Spring Boot

SQS is a queue that AWS runs for you: producers send messages, consumers poll for them, and nothing is lost if a consumer is down. It also delivers some messages twice and, in standard queues, out of order. This page explains how SQS delivery really works, shows the Spring Cloud AWS 4 listener and template, and runs the consumer patterns that make duplicates harmless.

Share

Contents

How SQS delivers messages

Amazon Simple Queue Service is a message queue run by AWS. A producer sends a message to a queue, SQS stores it redundantly across several machines, and a consumer later asks for messages, processes them and deletes them. There is no server to run and no connection to keep open: every operation is an HTTPS call to the SQS API.

The key to SQS is what happens between receiving and deleting a message:

  • Visibility timeout: a received message is not removed, only hidden from other consumers for the visibility timeout, 30 seconds by default and at most 12 hours. If the consumer deletes it in that time, it is gone. If not, because the consumer crashed, threw an exception or was too slow, the message becomes visible again and is delivered to another consumer.
  • Receive count: each delivery increases the message's ApproximateReceiveCount, so a consumer can tell a first attempt from a retry.
  • Dead-letter queue: a redrive policy with a maxReceiveCount moves a message that keeps failing to a second queue, instead of retrying it until it expires. Messages are kept for 4 days by default and up to 14.
  • Long polling: a receive call can wait up to 20 seconds for a message to arrive, which avoids paying for empty responses. A receive returns at most 10 messages.

The consequence is that SQS delivers every message at least once. A consumer that processes a message and then fails to delete it in time, for example because the deletion call timed out, sees the message again. Every SQS consumer must therefore cope with duplicates. There are two kinds of queue:

Standard and FIFO queues
PropertyStandard queueFIFO queue (name ends in .fifo)
OrderBest effort; messages can arrive out of orderStrict order within each message group
DuplicatesOccasional duplicate deliveriesDuplicate sends removed within a 5-minute window, by deduplication ID
ThroughputNearly unlimitedLower limits, raised by high-throughput mode
ParallelismAny message to any consumerOne message group is processed by one consumer at a time
Best forIndependent jobs: emails, thumbnails, notificationsChanges that must be applied in order, such as one account's transactions

Even a FIFO queue does not remove the need for idempotent consumers: its deduplication applies to sends, while a message that is received but not deleted in time is still delivered again. A message body can be up to 1 MiB.

In Spring Boot, SQS support comes from Spring Cloud AWS, a community project under the awspring organisation. Version 4.0 added support for Spring Boot 4 and Spring Framework 7, and 4.2 is current. Neither Spring Cloud AWS nor an SQS endpoint is available where this page was built, so its listener and template examples are marked as not run; they were checked against the Spring Cloud AWS 4 reference documentation. The two programs that are shown running use only Spring Framework and an in-memory database, and show what the consumer code does with each message.

Setting up Spring Cloud AWS (not run)

Spring Cloud AWS publishes a bill of materials and one starter per service. The SQS starter brings the AWS SDK 2 SqsAsyncClient, the listener infrastructure and SqsTemplate:

XML
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>io.awspring.cloud</groupId>
            <artifactId>spring-cloud-aws-dependencies</artifactId>
            <version>4.2.1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependency>
    <groupId>io.awspring.cloud</groupId>
    <artifactId>spring-cloud-aws-starter-sqs</artifactId>
</dependency>
YAML
spring:
  cloud:
    aws:
      region:
        static: eu-west-1
      # for LocalStack in development and tests; leave unset in AWS
      endpoint: http://localhost:4566
      sqs:
        listener:
          max-inflight-messages-per-queue: 10   # default 10
          max-messages-per-poll: 10             # default 10, the SQS maximum
          poll-timeout: 10s                     # long polling wait, default 10 seconds

Credentials come from the AWS SDK's default chain: environment variables, the shared ~/.aws profile, or, on AWS, the IAM role of the EC2 instance, ECS task or EKS pod. Do not put access keys in application.yml; give the role only the SQS actions it needs, such as sqs:ReceiveMessage, sqs:DeleteMessage, sqs:GetQueueUrl and sqs:GetQueueAttributes for a consumer.

Sending with SqsTemplate (not run)

SqsTemplate converts a Java object to a JSON body and sends it. Simple sends take the queue name and the payload; the fluent form sets headers, a delay and, for FIFO queues, the message group:

Java
@Service
public class OrderEvents {
    private final SqsTemplate sqs;

    public OrderEvents(SqsTemplate sqs) {
        this.sqs = sqs;
    }

    public void orderPlaced(OrderPlaced event) {
        sqs.send("order-events", event);                      // JSON body
    }

    public void paymentChanged(String accountId, PaymentChanged event) {
        sqs.send(to -> to.queue("payments.fifo")
                .payload(event)
                .messageGroupId(accountId)                    // order kept per account
                .messageDeduplicationId(event.paymentId()));  // repeated sends removed
    }

    public void remindLater(Reminder reminder) {
        sqs.send(to -> to.queue("reminders")
                .payload(reminder)
                .delaySeconds(900));                          // the 15-minute maximum
    }
}
  • A failed send throws MessagingOperationFailedException, which carries the message so that it can be logged or retried.
  • For FIFO queues the group ID decides the ordering. If none is given, Spring Cloud AWS generates a random UUID, which keeps the send working but gives up ordering between messages.
  • Batch sends are limited by SQS to 10 messages per request.
  • Sending to SQS inside a database transaction does not make the send transactional. If the transaction rolls back after the send, the message has already gone. Send after the commit, with @TransactionalEventListener, or use the transactional outbox pattern: write the message to an outbox table in the same transaction and publish it from there.

Receiving with @SqsListener (not run)

An annotated method receives messages from a queue. The container polls with long polling, converts the JSON body to the parameter type, calls the method on a pool of threads and deletes the message when the method returns:

Java
@Component
public class OrderListener {

    @SqsListener(value = "order-events", maxConcurrentMessages = "20",
            messageVisibilitySeconds = "120")
    public void onOrder(OrderPlaced event,
            @Header(MessageSystemAttributes.SQS_APPROXIMATE_RECEIVE_COUNT) String receiveCount) {
        // runs once per message; throwing leaves the message on the queue
        fulfilment.start(event.orderId());
    }

    @SqsListener("thumbnail-requests")
    public void onBatch(List<Message<ThumbnailRequest>> batch) {
        // a List parameter switches the listener to batch mode
        batch.forEach(m -> thumbnails.render(m.getPayload()));
    }
}
  • maxConcurrentMessages limits how many messages from this queue are in progress at once. Set messageVisibilitySeconds comfortably longer than the slowest normal processing time, or slow messages are delivered a second time while the first attempt is still running.
  • Message attributes arrive as headers prefixed with Sqs_MA_. System attributes, such as the receive count, have their own prefix, and SqsHeaders and its nested MessageSystemAttributes class hold the header names as constants.
  • Since Spring Cloud AWS 4.1 the listener containers can run on virtual threads, and since 4.0 one listener can dispatch different message types to several @SqsHandler methods.

The JSON conversion is done by Spring Messaging, with Jackson 3 in Spring Cloud AWS 4. This program runs the same Jackson message converter on bodies like those an SQS listener receives, including a newer and an older version of the event and a body that is not JSON:

Java
import java.math.BigDecimal;
import java.util.Map;
import org.springframework.messaging.Message;
import org.springframework.messaging.converter.JacksonJsonMessageConverter;
import org.springframework.messaging.converter.MessageConversionException;
import org.springframework.messaging.support.MessageBuilder;

public class PayloadConversion {

    record OrderPlaced(String orderId, BigDecimal total) {
    }

    record OrderPlacedV2(String orderId, BigDecimal total, String currency) {
    }

    public static void main(String[] args) {
        JacksonJsonMessageConverter converter = new JacksonJsonMessageConverter();
        converter.setStrictContentTypeMatch(false);

        // a message body as it arrives from SQS: a JSON string
        Message<String> message = MessageBuilder
                .withPayload("{\"orderId\":\"A-1\",\"total\":42.50}")
                .copyHeaders(Map.of("Sqs_MA_eventType", "order-placed"))
                .build();
        Object order = converter.fromMessage(message, OrderPlaced.class);
        System.out.println("As OrderPlaced  : " + order);

        // a newer consumer with an extra field still reads the old message
        Object v2 = converter.fromMessage(message, OrderPlacedV2.class);
        System.out.println("As OrderPlacedV2: " + v2);

        // a producer added a field the old consumer does not know
        Message<String> newer = MessageBuilder
                .withPayload("{\"orderId\":\"A-2\",\"total\":10,\"currency\":\"EUR\"}").build();
        System.out.println("Newer message as OrderPlaced: "
                + converter.fromMessage(newer, OrderPlaced.class));

        // a body that is not JSON at all: a poison message
        Message<String> broken = MessageBuilder.withPayload("order A-3 placed").build();
        try {
            converter.fromMessage(broken, OrderPlaced.class);
        } catch (MessageConversionException e) {
            System.out.println("Not JSON: " + e.getClass().getSimpleName());
        }
    }
}
Output
As OrderPlaced  : OrderPlaced[orderId=A-1, total=42.50]
As OrderPlacedV2: OrderPlacedV2[orderId=A-1, total=42.50, currency=null]
Newer message as OrderPlaced: OrderPlaced[orderId=A-2, total=10]
Not JSON: MessageConversionException
  • The JSON body became an OrderPlaced record, with total as the exact BigDecimal 42.50.
  • A consumer whose record has an extra currency field read the old message, and the missing field was null. New fields must therefore be optional for consumers.
  • An old consumer read a newer message with an unknown currency property without failing. Jackson 3 ignores unknown properties by default, while plain Jackson 2 failed on them by default. That lets producers add fields before every consumer is upgraded.
  • A body that is not JSON threw MessageConversionException before the method was called. In SQS, such a poison message fails on every delivery, which is exactly what a dead-letter queue is for.

Acknowledgement and failure handling (not run)

Acknowledging a message means deleting it from the queue. The listener's acknowledgementMode decides when that happens:

Acknowledgement modes in Spring Cloud AWS 4
ModeDeleted whenUse for
ON_SUCCESS (default)The method returns without an exceptionMost listeners: a failure is retried after the visibility timeout
ALWAYSThe method returns or throwsMessages that must not be retried, where losing one is acceptable
MANUALThe code calls Acknowledgement.acknowledge()Asynchronous processing, or deciding per message inside a batch
Java
@SqsListener(value = "invoices", acknowledgementMode = "MANUAL")
public void onInvoice(Invoice invoice, Acknowledgement ack) {
    if (archive.store(invoice)) {
        ack.acknowledge();          // delete now
    }                               // otherwise SQS redelivers after the visibility timeout
}
  • With the default mode, an exception from the method leaves the message on the queue. It becomes visible again when its visibility timeout expires, and is received again with a higher receive count.
  • Acknowledgements are sent in batches to save API calls: for standard queues, after 1 second or 10 messages, whichever comes first. For FIFO queues they are sent at once, to keep the order.
  • Configure a dead-letter queue on every queue, with a maxReceiveCount such as 5. Without one, a poison message is retried until the retention period ends, using a consumer thread each time.
  • For a delay between retries, the listener's ErrorHandler or AsyncErrorHandler can change the message's visibility timeout. Spring Cloud AWS 4.0 added exponential and linear backoff error handlers that compute the delay from the receive count.

In a FIFO queue, the messages of one group are processed in order, one at a time, while different groups run in parallel. If one message fails, the following messages of the same group in that batch are discarded and come back with it after the visibility timeout, so the order is kept. A message that always fails therefore blocks its whole group until it reaches the dead-letter queue.

Making duplicates harmless

Because any message can arrive twice, the listener's work must be idempotent: running it twice must have the same effect as running it once. The most reliable way is to record each message ID in the same database transaction as the work. In this program, message m-1 is delivered a second time, as SQS would after a lost acknowledgement:

Java
import java.util.List;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionTemplate;

public class IdempotentConsumer {

    record Delivery(String messageId, String orderId, int receiveCount) {
    }

    private final JdbcTemplate jdbc;
    private final TransactionTemplate tx;

    IdempotentConsumer(JdbcTemplate jdbc, TransactionTemplate tx) {
        this.jdbc = jdbc;
        this.tx = tx;
    }

    // what an @SqsListener method body would do with each delivery
    void handle(Delivery d) {
        try {
            tx.executeWithoutResult(status -> {
                // the key insert and the business write share one transaction
                jdbc.update("INSERT INTO processed_messages VALUES (?)", d.messageId());
                jdbc.update("UPDATE orders SET status = 'PAID' WHERE id = ?", d.orderId());
                jdbc.update("INSERT INTO emails VALUES (?)", "receipt for " + d.orderId());
            });
            System.out.println("  " + d + ": processed");
        } catch (DuplicateKeyException e) {
            // already done: acknowledge the message so that SQS deletes it
            System.out.println("  " + d + ": duplicate, skipped");
        }
    }

    public static void main(String[] args) {
        var dataSource = new DriverManagerDataSource("jdbc:h2:mem:sqs;DB_CLOSE_DELAY=-1");
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);
        jdbc.execute("CREATE TABLE processed_messages (message_id VARCHAR(40) PRIMARY KEY)");
        jdbc.execute("CREATE TABLE orders (id VARCHAR(10) PRIMARY KEY, status VARCHAR(10))");
        jdbc.execute("CREATE TABLE emails (text VARCHAR(40))");
        jdbc.update("INSERT INTO orders VALUES ('A-1', 'NEW'), ('A-2', 'NEW')");
        var consumer = new IdempotentConsumer(jdbc,
                new TransactionTemplate(new DataSourceTransactionManager(dataSource)));

        // SQS delivers at least once: m-1 arrives again, for example after the
        // first consumer's acknowledgement was lost or its visibility timeout expired
        System.out.println("Deliveries:");
        for (Delivery d : List.of(new Delivery("m-1", "A-1", 1), new Delivery("m-2", "A-2", 1),
                new Delivery("m-1", "A-1", 2))) {
            consumer.handle(d);
        }
        System.out.println("Orders: " + jdbc.queryForList(
                "SELECT id || '=' || status FROM orders ORDER BY id", String.class));
        System.out.println("Emails: " + jdbc.queryForList("SELECT text FROM emails",
                String.class));
    }
}
Output
Deliveries:
  Delivery[messageId=m-1, orderId=A-1, receiveCount=1]: processed
  Delivery[messageId=m-2, orderId=A-2, receiveCount=1]: processed
  Delivery[messageId=m-1, orderId=A-1, receiveCount=2]: duplicate, skipped
Orders: [A-1=PAID, A-2=PAID]
Emails: [receipt for A-1, receipt for A-2]
  • The first deliveries of m-1 and m-2 inserted their IDs, marked orders A-1 and A-2 as paid, and queued one receipt each.
  • The second delivery of m-1, with receive count 2, failed on the primary key of processed_messages. The whole transaction rolled back, so the order was not updated again and no second receipt was written. The handler treated DuplicateKeyException as success, so the message is deleted.
  • The final state has each order paid once and exactly two receipts, the same as if every message had arrived once.

Two details make this work. The key is inserted in the same transaction as the business change, so either both happen or neither does; checking "was this processed?" in one step and doing the work in another leaves a gap in which a crash causes the duplicate anyway. And the database's unique constraint decides, not a read before the write, so two consumers that receive the same message at the same moment cannot both succeed. Effects outside the database, such as calling a payment API, need the same idea on the other side: pass the message ID as an idempotency key, if the API accepts one.

Some work is naturally idempotent and needs no table: setting a status to PAID or writing a file under a fixed name gives the same result twice. Incrementing a counter or sending an email does not.

Testing SQS code

  • Unit tests: call the listener method directly with a payload, as with any other bean method. Most of the logic, including idempotency, is tested this way.
  • LocalStack: the LocalStack container emulates SQS and other AWS services. With Testcontainers, start it in the test and point spring.cloud.aws.endpoint at it with @DynamicPropertySource, as the Testcontainers page explains.
  • Awaitility: a listener runs on another thread, so tests wait for its effect with await().atMost(Duration.ofSeconds(10)).untilAsserted(...) instead of sleeping. Awaitility comes with spring-boot-starter-test.
  • Startup without AWS: spring.cloud.aws.sqs.listener.auto-startup=false, added in 4.0, keeps the listener containers from polling in tests that do not need them.

Choosing a queue and a setting

SQS choices for common situations
SituationChoice
Independent background jobsStandard queue, @SqsListener with ON_SUCCESS
Changes that must be applied in order per entityFIFO queue, message group ID = entity ID
Processing that sometimes takes minutesmessageVisibilitySeconds above the slowest normal run
Messages that keep failingDead-letter queue with maxReceiveCount, and an alarm on its depth
Any consumer at allIdempotent processing: message ID stored in the same transaction
Sending from a database transactionSend after commit, or a transactional outbox
One event to many consumersAn SNS topic with one SQS queue per consumer
Replaying old messages or very high throughput streamsKafka or Kinesis instead of SQS

SQS is the simplest reliable queue on AWS: no brokers to run, and failures are retried by design. The price is duplicates and, in standard queues, unordered delivery, so design the consumer for both from the start. For a broker that keeps messages for replay and orders them per partition, compare the Kafka listener page; for other AWS services from Spring, see DynamoDB and Lambda.