Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Using Spring Cloud AWS 3.x, write a listener that consumes messages from an SQS queue named orders and converts JSON to an Order record. What happens if the listener throws?

We add spring-cloud-aws-starter-sqs and write a method annotated @SqsListener("orders") that takes an Order record; Jackson converts the JSON body to the parameter type, and the message converter can be configured when type headers are missing or ambiguous. If the method throws, the message is not acknowledged, so it stays in the queue and becomes visible again after the visibility timeout, which means processing must be idempotent. A redrive policy on the SQS queue moves a message to a dead-letter queue after a set number of receives. Spring Cloud AWS 3.x is a community project under awspring, rebuilt on AWS SDK v2.

Why this question is asked

Queue listeners look trivial: one annotation and a method. The interesting part is what happens when the method fails, because that decides whether a message is lost, processed twice or retried forever. Interviewers ask this coding question to check that we understand SQS's delivery model and not just the annotation. In this answer, we will recap how SQS delivers messages, write the listener, see how the JSON becomes an Order, follow a failing message through retries, and set up the dead-letter queue that stops poison messages.

1A Quick Recap of SQS Delivery

Amazon SQS is a managed message queue. A consumer receives a message, processes it and then deletes it. Receiving does not remove the message; it only hides it from other consumers for the visibility timeout, 30 seconds by default. If the consumer does not delete it within that time, the message becomes visible again and some consumer receives it again.

This is at-least-once delivery: a message is never lost by a crashing consumer, but it can be delivered more than once, for example if processing takes longer than the visibility timeout or if the consumer crashes after doing the work but before deleting the message. Standard queues can also, rarely, deliver a message twice on their own. So any consumer must be prepared to see the same message again.

2Writing the Listener

Spring Cloud AWS 3.x is maintained by the awspring community, not by AWS or the core Spring team, and was rebuilt on AWS SDK for Java v2. Its SQS starter auto-configures an async SQS client from the default credentials and region, and a listener container that polls the queue.

Java
// build.gradle: implementation "io.awspring.cloud:spring-cloud-aws-starter-sqs"
// (versions come from the spring-cloud-aws-dependencies BOM, 3.x)
public record Order(String orderId, String customerId, BigDecimal total) { }
@Component
class OrderListener {
private final OrderService orders;
OrderListener(OrderService orders) { this.orders = orders; }
@SqsListener("orders") // queue name, or its URL
void handle(Order order) {
orders.process(order);
}
}
// message body: {"orderId":"o-17","customerId":"c-4","total":49.90}
// -> handle(Order[orderId=o-17, customerId=c-4, total=49.90])
// method returns normally -> message deleted from the queue

Notice that the listener takes the Order directly. By default the container acknowledges, which in SQS means deletes, the message only after the method returns successfully. We can also take a Message<Order> to read headers such as the receive count, or an Acknowledgement parameter for manual acknowledgement.

3How the JSON Becomes an Order

The listener container uses a messaging converter backed by Jackson. It reads the message body as JSON and converts it to the method's parameter type, here Order. Messages sent with Spring Cloud AWS's SqsTemplate also carry a header naming the payload's Java type, which the converter can use.

Messages from other producers, such as a Node.js service or an SNS subscription, do not carry that header. In the common case the converter uses the parameter type and all is well. Problems appear when the type header names a class that does not exist in the consumer, or when the body is wrapped, as SNS does unless raw message delivery is enabled. Then we configure the converter, for example telling it to ignore type headers and always use the parameter type, or use the @SnsNotificationMessage annotation to unwrap SNS envelopes. The exact options vary between 3.x releases, so check your version's documentation.

4What Happens When the Listener Throws

Suppose process() throws because the customer does not exist yet, or because a database is briefly down. The container catches the exception, logs it and does not delete the message. After the visibility timeout, the message becomes visible and is received again, by this instance or another one. This repeats every 30 seconds or so for as long as the failure lasts.

Java
@SqsListener("orders")
void handle(Order order, @Header("Sqs_Msa_ApproximateReceiveCount") String receiveCount) {
log.info("order {} attempt {}", order.orderId(), receiveCount);
orders.process(order); // throws IllegalStateException
}
// 10:00:00 order o-17 attempt 1 -> exception, message not deleted
// 10:00:30 order o-17 attempt 2 -> exception again
// 10:01:00 order o-17 attempt 3 -> succeeds, message deleted
// (header name as an example; check your version for the exact constant)
Step throughA failing message returns until it succeeds or moves to the DLQ
orders queueListenerOrderServiceorders-dlq
receive o-17 (receive count 1)
process(order)
exception: message not deleted
visibility timeout ends: o-17 visible again
receive o-17 (receive count 2)
process(order)
exception again
after maxReceiveCount = 5: move o-17 to the DLQ

8 messages in order. Play them, or step through them one at a time.

So a temporary failure heals by itself, which is good. But it means the same order can reach process() several times, and also that work done before the exception, such as sending an email, may be repeated. Processing must be idempotent: running it twice for the same message has the same effect as running it once. A common way is to record processed order ids in a table with a unique key and skip ids already present, inside the same transaction as the work.

5Stopping Poison Messages With a Dead-Letter Queue

Some messages will never succeed: a body that is not valid JSON, an order with a negative total, a bug in our code for one kind of order. Without protection, such a poison message is received and fails forever, wasting capacity and filling logs. The fix is on the SQS side, not in Spring: a redrive policy on the orders queue names a dead-letter queue and a maxReceiveCount. After a message has been received that many times without being deleted, SQS moves it to the dead-letter queue.

Java
# Created with infrastructure code, for example with the AWS CLI:
aws sqs create-queue --queue-name orders-dlq
aws sqs set-queue-attributes --queue-url https://sqs.eu-west-1.amazonaws.com/123456789012/orders \
--attributes '{"RedrivePolicy":"{\"deadLetterTargetArn\":\"arn:aws:sqs:eu-west-1:123456789012:orders-dlq\",\"maxReceiveCount\":\"5\"}"}'

We then alert on the dead-letter queue's message count, inspect what arrived there, fix the cause and redrive the messages back to the main queue. Notice that a conversion failure, such as invalid JSON, also counts as a failed receive, so it ends up in the dead-letter queue too instead of looping.

6Follow-up questions

What if processing takes longer than the visibility timeout?

The message becomes visible while we are still working, and another consumer may start processing it in parallel. We either set the queue's visibility timeout comfortably above the longest processing time, or extend the visibility of the message while working. Idempotency protects us in either case.

Can we retry faster than the visibility timeout?

Yes. Spring Cloud AWS lets an error handler or acknowledgement setup change the message's visibility on failure, for example to 5 seconds for a quick retry or to a growing value for backoff. Check your version for the exact interfaces.

Should we use a FIFO queue to avoid duplicates?

A FIFO queue gives ordering per message group and deduplication of sends within five minutes, but a consumer that fails still receives the message again. So FIFO reduces duplicates from producers, not the need for idempotent processing.

7Conclusion

In this answer, we wrote an SQS listener with spring-cloud-aws-starter-sqs and @SqsListener("orders"), let Jackson convert the JSON body to an Order record, and saw when the converter needs configuration. We followed a failing message: it is not deleted, returns after the visibility timeout and is processed again, so the listener must be idempotent, and a redrive policy on the queue moves poison messages to a dead-letter queue after a set number of receives.

What to say in the interviewAbout 90 seconds aloud

Open with

I would add spring-cloud-aws-starter-sqs from the Spring Cloud AWS 3.x BOM; that is the awspring community project, rebuilt on AWS SDK v2. Then a component with a method annotated @SqsListener with the queue name orders, taking an Order record as its parameter.

Then, if they want more

The listener container converts the JSON body with Jackson into the parameter type.

Messages sent through SqsTemplate carry a type header; messages from other producers do not, which is normally fine, but if a type header points to a class we do not have, or SNS wraps the body, I would configure the converter to use the parameter type or unwrap the SNS envelope.

If the method returns normally, the message is acknowledged, which means deleted. If it throws, it is not deleted, so after the visibility timeout, 30 seconds by default, it becomes visible and is received again.

That gives automatic retry for temporary failures, but it also means the same order can be processed more than once, so processing has to be idempotent, for example by recording processed order ids under a unique constraint in the same transaction.

For messages that can never succeed, I would configure a redrive policy on the queue itself, with a dead-letter queue and a maxReceiveCount such as 5, alert on the dead-letter queue's depth, fix the cause and redrive. I would also make sure the visibility timeout is longer than the slowest processing time.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Using Spring Cloud AWS 3.x, write a listener that consumes messages from an SQS queue...": https://scrivio-interview-library.netlify.app/spring-boot/spring-cloud/56b38f9a4b/