📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Compare Amazon SQS and SNS with Azure Service Bus. How do you fan out one event to several consumers on AWS, what do FIFO queues and message groups give you, how does the visibility timeout differ from Service Bus peek-lock, and how do dead-letter queues and redrive work?

Compares SQS and SNS with Azure Service Bus: queues vs topics, SNS-to-SQS fan-out with filter policies, FIFO queues with message group ids and deduplication, visibility timeout vs peek-lock, and dead-letter queues with maxReceiveCount and redrive.

Mid-Level Theory Intermediate amazon-sns amazon-sqs aws azure-service-bus devops messaging

🎯 Key points

  • Service Bus is one broker (queues, topics, subscriptions, sessions); AWS splits it into SQS (queues) and SNS (pub/sub)
  • Fan-out: SNS topic to one SQS queue per consumer, with subscription filter policies and raw message delivery
  • SQS standard: at-least-once, best-effort ordering, nearly unlimited throughput; the default when order doesn't matter
  • SQS FIFO: order per MessageGroupId, deduplication within 5 minutes; 300 TPS per action without batching (3,000 msg/s with batches of 10) unless high-throughput mode; one in-flight message per group adds head-of-line latency
  • Visibility timeout (default 30 s, max 12 h) hides a received message; delete it to complete, ChangeMessageVisibility to extend
  • Service Bus peek-lock: lock (default 60 s, max 5 min) with Complete, Abandon, DeadLetter and lock renewal
  • DLQ via redrive policy maxReceiveCount (Service Bus MaxDeliveryCount, default 10); redrive back to source after a fix
  • Consumers must be idempotent on both; SQS max message raised from 256 KiB to 1 MiB in August 2025, larger payloads via S3 claim check

⏱ 30-second answer

Service Bus is one broker with queues, topics, subscriptions and sessions. On AWS that is split: SQS for queues and SNS for pub/sub. To fan out, publish to an SNS topic that delivers to one SQS queue per consumer, filtered with subscription filter policies, so each consumer gets its own backlog, retries and DLQ.

SQS standard is at-least-once with best-effort ordering. SQS FIFO orders by MessageGroupId (like Service Bus sessions) and deduplicates within 5 minutes, at lower throughput.

Instead of a peek-lock, SQS uses a visibility timeout: a received message is hidden until you delete it or the timeout expires. After maxReceiveCount receives it moves to the DLQ, and you can redrive it later.

The trade-off: SQS and SNS are simpler and scale further; Service Bus gives richer broker features in one place.

🗣 Full answer (senior)

How I would answer this in an interview

"The biggest difference is shape. Service Bus gives me queues and topics with subscriptions, sessions, scheduled messages and duplicate detection in one broker. AWS splits that into SQS for point-to-point queues and SNS for publish/subscribe. So the AWS version of a Service Bus topic with three subscriptions is usually an SNS topic with three SQS queues subscribed. Each consumer gets its own durable queue, its own retry behaviour and its own dead-letter queue, and I use filter policies on the subscriptions so, say, the fraud service only gets orders over a threshold. I turn on raw message delivery so the consumer gets my JSON, not the SNS envelope.

For locking, Service Bus uses peek-lock: I receive a message, it's locked for up to five minutes, and I complete, abandon or dead-letter it, renewing the lock for long work. SQS uses a visibility timeout: when I receive a message it's hidden for, by default, 30 seconds; if I delete it, it's done; if I don't, it reappears and its receive count goes up. For long work I call ChangeMessageVisibility to extend it. Once the receive count passes the queue's maxReceiveCount, SQS moves it to the DLQ. After fixing the bug I use DLQ redrive to send messages back to the source queue.

Ordering is where people get caught. SQS standard queues are at-least-once with only best-effort ordering. If I need order, I use a FIFO queue and set a MessageGroupId, such as the order id. Messages in a group are delivered in order, one at a time, which is the same idea as Service Bus sessions. FIFO also deduplicates messages with the same deduplication id within five minutes, but only on send; it doesn't make my consumer exactly-once. The mistake I see is trusting that dedup and skipping idempotency. On both clouds my consumer still has to be idempotent."


Feature comparison

Feature Azure Service Bus Amazon SQS + SNS
Queue Queue SQS queue (standard or FIFO)
Pub/sub Topic + subscriptions (with SQL/correlation filters) SNS topic + subscriptions (filter policies) to SQS, Lambda, HTTP
Locking Peek-lock, lock duration default 60 s, max 5 min, renewable Visibility timeout default 30 s, max 12 h, extendable
Complete CompleteMessageAsync DeleteMessage with the receipt handle
Retry count MaxDeliveryCount (default 10) Redrive policy maxReceiveCount
DLQ Built-in sub-queue per entity Separate SQS queue you configure; redrive back to source
Ordering Sessions FIFO queue, MessageGroupId
Duplicate detection Configurable window on the entity FIFO only, 5-minute window, deduplication id or content-based
Scheduling Scheduled enqueue time, any time in the future Delay up to 15 minutes; use EventBridge Scheduler for later
Max message size 256 KB Standard, up to 100 MB Premium 1 MiB (since August 2025); S3 claim check beyond that
Retention Up to 14 days (Standard), longer on Premium 1 minute to 14 days, default 4 days
Receive AMQP, push-like processor HTTPS polling; long polling up to 20 s

When to use which pattern on AWS

Need AWS choice
One producer, one consumer, high volume SQS standard
Strict order per entity (order id, account id) SQS FIFO with MessageGroupId
One event, many independent consumers SNS topic to one SQS queue per consumer
Content-based routing across many targets, SaaS events EventBridge
AMQP or JMS compatibility for existing code Amazon MQ

Production example

An OrderPlaced event moved from a Service Bus topic with three subscriptions to an SNS topic with three SQS queues. Billing needed per-order ordering, so its queue became FIFO behind a FIFO topic with MessageGroupId = orderId. A visibility timeout set lower than the PDF step's real duration caused [4%] duplicate invoices until the timeout was set to six times the p99 processing time and the handler checked an idempotency table, which brought duplicates to zero.

🔍 What the interviewer is checking

Checks whether the candidate understands broker semantics well enough to move a Service Bus design to SQS and SNS without losing correctness.

Green flags

  • Explains SNS-to-SQS fan-out with a queue per consumer
  • Explains the visibility timeout correctly and links it to duplicate processing
  • Knows FIFO ordering is per MessageGroupId and deduplication is a 5-minute send-side window
  • Insists on idempotent consumers and watched DLQs

Red flags

  • Thinks several consumers on one SQS queue each get every message
  • Believes FIFO gives exactly-once processing
  • Doesn't know what happens when a message isn't deleted

📚 Learn in depth

1. Two services instead of one broker

Azure:   Producer ─▶ Service Bus topic ─┬─▶ subscription: billing  ─▶ consumer
                                       ├─▶ subscription: shipping ─▶ consumer
                                       └─▶ subscription: fraud (filter) ─▶ consumer

AWS:     Producer ─▶ SNS topic ─┬─▶ SQS billing-queue  (+ billing-dlq)  ─▶ consumer
                                ├─▶ SQS shipping-queue (+ shipping-dlq) ─▶ consumer
                                └─▶ SQS fraud-queue (filter policy)    ─▶ consumer

SNS itself does not store messages for consumers; it pushes to subscribers. Putting SQS behind it gives durability, buffering and independent retry per consumer. Each queue needs an access policy that allows the SNS topic to sqs:SendMessage.

2. Visibility timeout, step by step

t=0    ReceiveMessage  ─▶ message hidden, ReceiveCount=1, receipt handle R1
t=5s   worker busy...
t=30s  timeout expires, not deleted ─▶ message visible again
t=31s  another worker receives it  ─▶ ReceiveCount=2, receipt handle R2
...    ReceiveCount > maxReceiveCount ─▶ moved to DLQ

If the first worker eventually finishes, its delete with R1 may fail or the work is done twice. So: set the visibility timeout above your worst realistic processing time, extend it with ChangeMessageVisibility for long jobs, and make processing idempotent. For an SQS-triggered Lambda, AWS recommends a queue visibility timeout of at least six times the function timeout.

Service Bus differs in that the lock is held by the broker on behalf of an AMQP link; the SDK's processor can renew it automatically (MaxAutoLockRenewalDuration).

3. FIFO mechanics

  • MessageGroupId: messages in one group are delivered in order; while one is in flight (received, not deleted), no later message in that group is delivered. Different groups are processed in parallel, so pick a key with many values (order id, not a constant).
  • Deduplication: messages with the same MessageDeduplicationId (or the same body hash with content-based deduplication) within 5 minutes are accepted but not delivered twice.
  • Throughput: without high-throughput mode, 300 transactions per second per API action (3,000 messages per second with batches of 10). High-throughput mode raises this to tens of thousands per second depending on the region; check the current SQS quotas page for yours.

4. Dead-letter queues and redrive

A DLQ is an ordinary SQS queue named in the source queue's redrive policy with maxReceiveCount. The DLQ must be the same type (FIFO for FIFO). Set the DLQ's retention longer than the source's, because the original enqueue timestamp is kept for standard queues. After you fix the cause, DLQ redrive (console, or StartMessageMoveTask API) moves messages back.

5. Delivery guarantees

Both platforms give at-least-once for normal consumption. FIFO deduplication and Service Bus duplicate detection remove duplicate sends within a window; they cannot stop a consumer from processing a message twice when it crashes after doing the work but before deleting or completing it. That is why the consumer records processed message ids (an inbox table) or makes the operation naturally idempotent.

6. Polling cost

SQS is pull over HTTPS and billed per request. Short polling returns immediately, often empty. Set WaitTimeSeconds up to 20 (long polling) and receive up to 10 messages per call to cut empty receives and cost.

Try it yourself

  1. Create an SNS topic and two SQS queues, subscribe both with raw message delivery, publish one message and see it in both.
  2. Add a filter policy ({"total": [{"numeric": [">", 1000]}]}) to one subscription and publish message attributes to test it.
  3. Receive a message with a 10-second visibility timeout, don't delete it, and watch ApproximateReceiveCount grow until it lands in the DLQ with maxReceiveCount = 3.
  4. Send the same message twice to a FIFO queue with the same deduplication id and confirm only one is delivered.
  5. Use the console's DLQ redrive to move the messages back to the source queue.

💻 Code

Publishing to SNS for fan-out, and an SQS consumer as a .NET 10 BackgroundService with long polling, visibility extension and idempotent processing.

// Publisher: one event, many consumers via SNS. MessageGroupId only applies to FIFO topics.
using System.Text.Json;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;

namespace Orders;

public sealed record OrderPlaced(Guid OrderId, decimal Total);

public sealed class OrderEvents(IAmazonSimpleNotificationService sns, IConfiguration config)
{
    public Task PublishAsync(OrderPlaced evt, CancellationToken ct) =>
        sns.PublishAsync(new PublishRequest
        {
            TopicArn = config["Messaging:OrderEventsTopicArn"],
            Message = JsonSerializer.Serialize(evt),
            MessageGroupId = evt.OrderId.ToString(),           // order kept per order
            MessageDeduplicationId = $"order-placed-{evt.OrderId}",
            MessageAttributes = new()
            {
                // Filter policies match on attributes, e.g. the fraud queue only takes large orders.
                ["total"] = new MessageAttributeValue { DataType = "Number", StringValue = evt.Total.ToString() }
            }
        }, ct);
}
// Consumer: long polling, delete only after success, idempotent by message id.
using Amazon.SQS;
using Amazon.SQS.Model;

namespace Billing;

public sealed class BillingConsumer(
    IAmazonSQS sqs, IConfiguration config, IProcessedMessages processed, ILogger<BillingConsumer> log)
    : BackgroundService
{
    private readonly string _queueUrl = config["Messaging:BillingQueueUrl"]!;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var response = await sqs.ReceiveMessageAsync(new ReceiveMessageRequest
            {
                QueueUrl = _queueUrl,
                MaxNumberOfMessages = 10,
                WaitTimeSeconds = 20,          // long polling: fewer empty, billed receives
                VisibilityTimeout = 120        // above p99 processing time
            }, stoppingToken);

            foreach (var message in response.Messages ?? [])
            {
                try
                {
                    // Redelivery after a crash is normal; skip work already done.
                    if (!await processed.TryMarkAsync(message.MessageId, stoppingToken))
                    {
                        await sqs.DeleteMessageAsync(_queueUrl, message.ReceiptHandle, stoppingToken);
                        continue;
                    }

                    await HandleAsync(message.Body, stoppingToken);
                    await sqs.DeleteMessageAsync(_queueUrl, message.ReceiptHandle, stoppingToken); // = Complete
                }
                catch (Exception ex) when (ex is not OperationCanceledException)
                {
                    // Not deleted: it reappears after the visibility timeout; after maxReceiveCount it goes to the DLQ.
                    log.LogError(ex, "Billing failed for message {MessageId}", message.MessageId);
                }
            }
        }
    }

    private static Task HandleAsync(string body, CancellationToken ct) => Task.CompletedTask;
}

public interface IProcessedMessages
{
    Task<bool> TryMarkAsync(string messageId, CancellationToken ct); // insert into an inbox table; false if present
}
// Redrive policy on billing-queue: after 5 failed receives, move to billing-dlq.
{
  "deadLetterTargetArn": "arn:aws:sqs:ap-southeast-2:111122223333:billing-dlq",
  "maxReceiveCount": "5"
}

Note: in a real handler, mark the message as processed in the same database transaction as the business change, so a crash between the two cannot lose or repeat the work.

⚠ Common mistakes

  • Mistake: Subscribing several consumers to one SQS queue to "fan out". Why it is wrong: SQS consumers compete; each message goes to only one of them. Instead: Publish to SNS and give each consumer its own SQS queue.
  • Mistake: Setting the visibility timeout shorter than the processing time. Why it is wrong: The message reappears and is processed twice while the first worker is still running. Instead: Set it above the p99 duration (six times the function timeout for Lambda) and extend it with ChangeMessageVisibility for long jobs.
  • Mistake: Relying on FIFO deduplication for exactly-once processing. Why it is wrong: It only removes duplicate sends within 5 minutes; a crash after the work but before DeleteMessage still causes a second delivery. Instead: Make the consumer idempotent with an inbox table or natural keys.
  • Mistake: Using a single constant MessageGroupId. Why it is wrong: The whole queue becomes one ordered lane processed one message at a time. Instead: Group by the entity that needs order, such as order id or account id.
  • Mistake: Short polling in a tight loop. Why it is wrong: Most receives return empty and you pay for every request. Instead: Use WaitTimeSeconds = 20 and batches of up to 10.
  • Mistake: No DLQ, or a DLQ nobody watches. Why it is wrong: Poison messages retry forever or silently pile up and expire. Instead: Configure a redrive policy, alarm on ApproximateNumberOfMessagesVisible on the DLQ, and use redrive after fixing the cause.
  • Mistake: Forgetting raw message delivery on SNS-to-SQS subscriptions. Why it is wrong: Consumers receive the SNS JSON envelope and fail to deserialise. Instead: Enable RawMessageDelivery, or unwrap the envelope deliberately.
  • Mistake: Expecting Service Bus-style scheduled messages days ahead. Why it is wrong: SQS delay is at most 15 minutes. Instead: Use EventBridge Scheduler or store the due time and poll.

🏛 Senior insight: trade-offs

A senior engineer moving from Service Bus to AWS keeps the same design rules (at-least-once delivery, idempotent consumers, a DLQ per consumer, ordering only where the business needs it) and maps the mechanisms rather than the names. SNS-to-SQS fan-out is often better than Service Bus subscriptions operationally, because each consumer's queue is a separate resource with its own metrics, alarms and IAM policy. What you lose is convenience: sessions, long-range scheduling and transactions across entities are not built in.

Measure with CloudWatch: ApproximateAgeOfOldestMessage for lag, ApproximateNumberOfMessagesVisible on DLQs, NumberOfEmptyReceives for polling waste.

Option When it fits Cost When not to
SQS standard High volume, order doesn't matter Per request, cheapest Per-entity ordering needed
SQS FIFO Per-entity ordering, dedup on send Higher per request, throughput quotas Very high volume with no ordering need
SNS + SQS Several independent consumers Two services to configure Single consumer
EventBridge Routing by content across many targets and accounts Per event Very high throughput at low cost
Service Bus Azure, rich broker semantics Tier-based (Premium for isolation) You're on AWS

🔗 Follow-ups the interviewer may ask

  1. When: Candidate compares SQS with Service Bus Why: Checks the wider broker picture: RabbitMQ and Kafka, retention and replay.
    How to answer

    Service Bus, RabbitMQ and SQS are queue brokers: a message is delivered, settled and gone. Kafka is a partitioned, retained log: messages stay for the retention period and each consumer group tracks an offset, so you can replay.

    • Ordering: Service Bus sessions, SQS FIFO message groups, Kafka per partition; RabbitMQ only per queue with a single consumer.
    • Guarantees: all are at-least-once in practice, so consumers deduplicate.
    • Operations: Service Bus and SQS are fully managed; RabbitMQ and self-hosted Kafka need a team (or Confluent Cloud / Event Hubs' Kafka endpoint).

    For a .NET system on Azure doing commands and business events, I default to Service Bus. I pick Kafka when I need high-volume streaming and replay. The trade-off is features and simplicity versus throughput and history.

  2. When: Candidate mentions FIFO message groups or sessions Why: Checks what breaks ordering and how to design without global order.
    How to answer

    Global ordering means one consumer processing one message at a time, which kills throughput, so real systems guarantee order per key: per order, customer or account.

    • Service Bus: set SessionId; a ServiceBusSessionProcessor locks a session to one receiver and processes it in order, while different sessions run in parallel.
    • Kafka: the message key picks the partition, and order holds within it. Adding partitions remaps keys.
    • SQS FIFO: the MessageGroupId works like a session.

    Order breaks with competing consumers, retries, dead-lettering and rebalances. Better still, design so order doesn't matter: version numbers with "ignore older", events that carry full state, or commutative updates. The trade-off is that per-key order lets one stuck message block every later message for that key.

  3. When: Candidate says FIFO deduplication prevents duplicates Why: Checks that they know exactly-once delivery is a myth and how to get effectively-once processing.
    How to answer

    At-most-once means settle first, then process: a crash loses the message. At-least-once means process first, then settle: a crash or lock expiry redelivers, so you get duplicates. Almost every real system chooses at-least-once.

    Exactly-once delivery is a myth because the acknowledgement itself can be lost after the work is done; the broker can't tell "not processed" from "processed but ack lost".

    • Kafka transactions give exactly-once only for read-process-write within Kafka.
    • Service Bus duplicate detection and SQS FIFO dedup only drop producer resends within a window.

    What you build is effectively-once processing: at-least-once delivery plus an idempotent consumer, using a natural idempotent write or an inbox row committed in the same transaction. The trade-off is extra storage and a unique-key check per message.

🛠 Real-world problems: how you handle them

Duplicate invoices after moving from Service Bus to SQS
Situation
A [billing] service in a .NET 10 system was moved from an Azure Service Bus subscription to an SQS queue behind SNS in ap-southeast-2. It generates a PDF invoice and emails the customer, about [40,000] orders a day. Customers started receiving two invoices.
Signals
Customer complaints about duplicate emails; CloudWatch showed `ApproximateReceiveCount` of 2–3 on many messages; the consumer logs showed the same MessageId processed twice about 35 seconds apart; p99 handler time in traces was [48 s] while the queue's visibility timeout was the default 30 s.
Investigation
Compared handler duration (OpenTelemetry traces in X-Ray) with the queue's `VisibilityTimeout` attribute via `aws sqs get-queue-attributes`. Grouped consumer logs by MessageId in CloudWatch Logs Insights to count repeats. Checked the old Service Bus code: it relied on automatic lock renewal in `ServiceBusProcessor`, which had no equivalent in the new polling loop. Confirmed there was no idempotency check before sending email.
Resolution
Immediately raised the visibility timeout to [300 s] and paused redrive. Then added an inbox table keyed on an idempotency key (order id plus event type) written in the same transaction as the invoice record, extended visibility with `ChangeMessageVisibility` every 60 s for long PDFs, and made the email step check the inbox before sending.
Prevention
A migration checklist that maps Service Bus lock duration, auto-renewal and MaxDeliveryCount to visibility timeout and maxReceiveCount; an integration test that runs the consumer with a short visibility timeout and asserts a single side effect; CloudWatch alarms on DLQ depth and on `ApproximateAgeOfOldestMessage`.

How to tell it (STAR)

**S:** We moved our billing consumer from Service Bus to SQS on AWS as part of [the platform move], and within a day customers were getting two invoices. **T:** I owned the consumer, so I had to stop the duplicates and find out why the migration caused them. **A:** I compared our trace durations with the queue settings and saw p99 processing was about 48 seconds while the visibility timeout was the default 30, so messages reappeared and a second worker picked them up. Service Bus had been renewing locks for us, and we had lost that silently. I raised the timeout right away, then added an inbox table written in the same transaction as the invoice, extended visibility during long PDFs, and added an integration test that forces redelivery. **R:** Duplicate invoices went from about [4%] of orders to zero, and the migration checklist now maps lock settings explicitly for [n] other consumers.

More in AWS

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me