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.
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
, so a consumer can tell a first attempt from a retry.ApproximateReceiveCount - Dead-letter queue: a redrive policy with a
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.maxReceiveCount - 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:
| Property | Standard queue | FIFO queue (name ends in .fifo |
|---|---|---|
| Order | Best effort; messages can arrive out of order | Strict order within each message group |
| Duplicates | Occasional duplicate deliveries | Duplicate sends removed within a 5-minute window, by deduplication ID |
| Throughput | Nearly unlimited | Lower limits, raised by high-throughput mode |
| Parallelism | Any message to any consumer | One message group is processed by one consumer at a time |
| Best for | Independent jobs: emails, thumbnails, notifications | Changes 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 SqsAsyncClientSqsTemplate
<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>
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 ~/.awsapplication.ymlsqs:ReceiveMessagesqs:DeleteMessagesqs:GetQueueUrlsqs:GetQueueAttributes
Sending with SqsTemplate (not run)
SqsTemplate
@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
, which carries the message so that it can be logged or retried.MessagingOperationFailedException - 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
, or use the transactional outbox pattern: write the message to an outbox table in the same transaction and publish it from there.@TransactionalEventListener
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:
@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()));
}
}
limits how many messages from this queue are in progress at once. SetmaxConcurrentMessages comfortably longer than the slowest normal processing time, or slow messages are delivered a second time while the first attempt is still running.messageVisibilitySeconds- Message attributes arrive as headers prefixed with
. System attributes, such as the receive count, have their own prefix, andSqs_MA_ and its nestedSqsHeaders class hold the header names as constants.MessageSystemAttributes - 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
methods.@SqsHandler
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:
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());
}
}
}
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
record, withOrderPlaced as the exacttotal 42.50.BigDecimal - A consumer whose record has an extra
field read the old message, and the missing field wascurrency . New fields must therefore be optional for consumers.null - An old consumer read a newer message with an unknown
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.currency - A body that is not JSON threw
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.MessageConversionException
Acknowledgement and failure handling (not run)
Acknowledging a message means deleting it from the queue. The listener's acknowledgementMode
| Mode | Deleted when | Use for |
|---|---|---|
ON_SUCCESS | The method returns without an exception | Most listeners: a failure is retried after the visibility timeout |
ALWAYS | The method returns or throws | Messages that must not be retried, where losing one is acceptable |
MANUAL | The code calls Acknowledgement.acknowledge() | Asynchronous processing, or deciding per message inside a batch |
@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
such as 5. Without one, a poison message is retried until the retention period ends, using a consumer thread each time.maxReceiveCount - For a delay between retries, the listener's
orErrorHandler 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.AsyncErrorHandler
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
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));
}
}
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
andm-1 inserted their IDs, marked orders A-1 and A-2 as paid, and queued one receipt each.m-2 - The second delivery of
, with receive count 2, failed on the primary key ofm-1 . The whole transaction rolled back, so the order was not updated again and no second receipt was written. The handler treatedprocessed_messages as success, so the message is deleted.DuplicateKeyException - 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
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
at it withspring.cloud.aws.endpoint , as the@DynamicPropertySourceTestcontainers page explains. - Awaitility: a listener runs on another thread, so tests wait for its effect with
instead of sleeping. Awaitility comes withawait().atMost(Duration.ofSeconds(10)).untilAsserted(...) .spring-boot-starter-test - Startup without AWS:
, added in 4.0, keeps the listener containers from polling in tests that do not need them.spring.cloud.aws.sqs.listener.auto-startup=false
Choosing a queue and a setting
| Situation | Choice |
|---|---|
| Independent background jobs | Standard queue, @SqsListenerON_SUCCESS |
| Changes that must be applied in order per entity | FIFO queue, message group ID = entity ID |
| Processing that sometimes takes minutes | messageVisibilitySeconds |
| Messages that keep failing | Dead-letter queue with maxReceiveCount |
| Any consumer at all | Idempotent processing: message ID stored in the same transaction |
| Sending from a database transaction | Send after commit, or a transactional outbox |
| One event to many consumers | An SNS topic with one SQS queue per consumer |
| Replaying old messages or very high throughput streams | Kafka 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