SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Message Queues
  • Pub/Sub
  • Message Brokers
  • Delivery Semantics
  • Dead Letter Queues
  • Kafka Deep Dive
  • Retries with Backoff
  • RabbitMQ and SQS
  • Event Streaming vs Message Queues
  • Message Ordering
  • Task Queues, Workers and Scheduled Jobs
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/Asynchronous Communication

RabbitMQ and SQS

Two popular queues: a flexible broker you run, and a managed queue in the cloud.

⏱ 14 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

RabbitMQ and Amazon SQS are two of the most common message queues. Both let one part of your system drop a message in a line, so another part can pick it up later.

  • RabbitMQ is a broker you run (or rent as a managed service). It is great at smart routing: one message can go to one queue, or to many, based on rules.
  • SQS is a fully managed queue from AWS. There is no server to run. It scales very far and is easy to use, but routing is simple.
  • Both are at-least-once in normal use, so your workers must handle a repeated message.

02Concept: What is it?

A message queue sits between a producer (who sends work) and a consumer (who does it). The producer does not wait. The queue keeps the message safe until a consumer is ready. (See Message Queues and Message Brokers for the basics.)

RabbitMQ: a broker with an exchange in front

In RabbitMQ a producer does not write straight to a queue. It sends the message to an exchange. The exchange looks at the message's routing key and at the bindings (rules that link the exchange to queues), and then copies the message into every queue that matches. Consumers read from the queues, and the broker pushes messages to them.

RabbitMQ: producer, exchange, queues, consumers
πŸ“€Producerkey: order.paid
→↓publish
πŸ”€Exchangereads key + bindings
→↓route
πŸ’³billing queue
πŸ“audit queue
→↓push
βš™οΈConsumersack when done
The exchange is the router. A queue only stores messages and hands them to its consumers.

SQS: a plain queue in the cloud

With SQS you create a queue and send messages to it. There is no exchange. Consumers pull messages by asking the queue. When a consumer receives a message, SQS does not delete it. It hides it for a while (the visibility timeout). If the consumer deletes the message in time, the work is done. If it crashes or is too slow, the message becomes visible again and another consumer gets it.

SQS: receive, hide, delete (or it comes back)
πŸ“€Producer
→↓send
πŸ“¬Queuemanaged by AWS
→↓receive (hidden)
βš™οΈWorkerthen delete
←no delete: reappears
Delete is the acknowledgement. No delete means the message returns after the visibility timeout.
🧠Push versus pull
RabbitMQ pushes messages to consumers (limited by a setting called prefetch, so a worker is not flooded). SQS consumers pull, and use long polling to wait for messages without hammering the service.

03Real-Life Example

🍡The Post Office and the Pickup Counter
RabbitMQ is like a sorting office. Letters arrive with an address code. The staff read the code and put a copy in the right pigeon-holes: billing, shipping, or both. Each department empties its own pigeon-hole. SQS is a pickup counter with one long shelf. A clerk takes a parcel and puts a "being handled" sticker on it. If the clerk comes back and removes the parcel, the job is done. If the clerk vanishes, the sticker expires and the parcel is back on the shelf for the next clerk.
Post office
Queues
The address code on a letter
The routing key
The sorting office
A RabbitMQ exchange
The rule "code starting with order goes to pigeon-hole 3"
A binding
The pigeon-hole
A queue
A "being handled" sticker on a parcel
SQS visibility timeout
Taking the parcel off the shelf for good
Ack (RabbitMQ) or delete (SQS)
A box for parcels that failed three times
Dead-letter queue
One order, two systems
RabbitMQ
🧾order.paid
↓topic exchange
πŸ’³billing
πŸ“audit
SQS
🧾order.paid
↓send to one queue
πŸ“¬orders queue

04Why Do We Need It?

πŸ”€Flexible routing (RabbitMQ)
Send one message to one queue, to many queues, or to the ones that match a pattern. Producers do not need to know who listens.
☁️Zero servers (SQS)
No brokers to patch, size or replicate. AWS runs it and it grows with your traffic.
🧯Work survives crashes
A message stays until a consumer confirms it. A crash does not lose the job.
🚦Smooth out bursts
A queue absorbs a spike, and workers drain it at their own speed.
☠️Poison message safety
Dead-letter queues catch messages that keep failing, so they do not block the rest.
🧩Loose coupling
Producers and workers can be written in different languages and deployed separately.
Pick RabbitMQ when you need smart routing and control. Pick SQS when you want a queue that just works and never needs a server.

05Where Do We Use It?

πŸ“§Background jobs
Send email, resize an image, generate a report: anything slow that the user should not wait for.
🧾Order pipelines
Payment, stock and shipping steps handled by separate workers, each with its own queue.
πŸ“£Fan-out
RabbitMQ fanout or topic exchanges, or SNS in front of several SQS queues, copy one event to many services.
Ξ»Serverless triggers
SQS is a common trigger for cloud functions, which scale with the queue length.
πŸ”Retry buffers
Put failed work on a delay or retry queue instead of blocking the main flow.
🏭Rate matching
Protect a slow database or a rate-limited partner API by letting a queue feed it at a safe speed.

06Types / Parts / How It Works

RabbitMQ exchange types

ExchangeHow it routesTypical use
DirectExact match of routing key and binding keySend a job to one named queue, e.g. 'billing'
TopicPattern match on a dotted key: * is one word, # is zero or more wordsorder.paid, order.refund.*, or order.# for audit
FanoutCopy to every bound queue, ignore the keyBroadcast an event to every interested service
HeadersMatch on message headers instead of the keyRare. Routing on several attributes at once

SQS queue types

TypeOrderingDuplicatesThroughput
StandardBest effort. Order may differ from send orderAt-least-once: a message may arrive twiceVery high, grows automatically
FIFOKept in order within a message group idDeduplication window removes repeats of the same idLower limits than standard (check the current limits)
πŸ“Note
Limits such as message size, retention time and FIFO throughput change over time. Check the current AWS and RabbitMQ documentation before you design around a number.

Side-by-side

QuestionRabbitMQSQS
Who runs it?You (or a managed host)AWS, fully managed
How are messages received?Broker pushes to consumers (prefetch limits)Consumers pull (long polling)
RoutingExchanges, bindings, patternsNone: one queue per destination (pair with SNS for fan-out)
AcknowledgementAck, nack, requeueDelete the message before the visibility timeout ends
ReplicationQuorum queues copy data across nodesHandled for you across zones
ProtocolsAMQP and others (MQTT, STOMP via plugins)AWS API over HTTPS
Dead lettersDead-letter exchange, TTLDead-letter queue with a max receive count
VisualizerRabbitMQ routing vs the SQS visibility timeoutOn the RabbitMQ side, switch the exchange type and publish different keys. On the SQS side, make the work slower than the visibility timeout, or make the worker crash.
Which side do you want to explore?
Exchange type
Exchange
topic
no message yet
β†’
πŸ’³ billing0 msg
bound to: order.paid, order.refund.*
πŸ“¦ shipping0 msg
bound to: order.shipped
πŸ“ audit0 msg
bound to: order.#
Published
0
Copies stored
0
across all queues
Dropped
0
matched no queue
Publish a message with a routing key. The exchange looks at the key and the bindings, and copies the message into every queue that matches.

Topic patterns: * is exactly one word, # is zero or more words. The bindings above are a fixed teaching example.

07How to Use It / Steps / Implementation

Using them well

  1. 1
    Make the work idempotent
    Both can deliver a message twice. Design the consumer so a repeat does no harm (see Idempotency).
  2. 2
    Acknowledge only after the work is done
    Ack or delete at the end, not at the start. Otherwise a crash loses the job.
  3. 3
    RabbitMQ: set durability on purpose
    Use durable queues and persistent messages if you cannot lose them, and use publisher confirms so the producer knows the broker has the message.
  4. 4
    RabbitMQ: set prefetch
    Limit how many unacknowledged messages one consumer holds, so one slow worker does not hoard the queue.
  5. 5
    SQS: size the visibility timeout
    Make it longer than the normal work time, and extend it if a job can run long. Too short means duplicate work, too long means slow recovery.
  6. 6
    Add a dead-letter queue
    After a set number of failed tries, move the message aside, alert someone and keep the main queue moving.
  7. 7
    Use long polling on SQS
    Wait up to a few seconds for messages instead of polling in a tight loop. It cuts empty responses and cost.
  8. 8
    Watch queue depth and age
    Alert on a growing backlog and on the age of the oldest message. They show a stuck or too-small worker pool.
A topic binding in RabbitMQ (illustrative)
exchange: orders (type: topic)
queue billing  <- binding "order.paid"
queue audit    <- binding "order.#"

publish key "order.paid"   -> billing, audit
publish key "order.shipped" -> audit
πŸ’‘Fan-out with SQS
SQS has no exchange, so for fan-out you usually publish to an SNS topic and subscribe several SQS queues to it. Each service then reads its own queue.

08Key Terms to Know

TermMeaning in easy words
Producer / consumerThe side that sends messages, and the side that receives and processes them
ExchangeRabbitMQ's router: it receives messages and copies them to queues by rule
BindingA rule that links an exchange to a queue, often with a key or pattern
Routing keyA label on a message (like order.paid) that the exchange uses to route it
Ack / nackA consumer's reply: done (ack) or failed (nack, optionally put back)
PrefetchHow many unacknowledged messages RabbitMQ lets one consumer hold at once
Quorum queueA RabbitMQ queue copied across several nodes, so it survives a node loss
Visibility timeoutThe time SQS hides a received message, waiting for the consumer to delete it
Long pollingWaiting on the SQS server for messages to arrive, instead of returning empty at once
FIFO queue / message groupAn SQS queue that keeps order inside each message group id
Dead-letter queue (DLQ)A queue for messages that failed too many times

09Pros, Cons and Trade-offs

βœ… Pros
  • Decouple producers from slow or unreliable workers
  • RabbitMQ: rich routing and several protocols
  • SQS: no servers, scales automatically
  • Messages survive consumer crashes
  • Dead-letter queues contain bad messages
⚠️ Cons
  • At-least-once means you must handle duplicates
  • RabbitMQ: you run, monitor and upgrade the cluster
  • SQS: simple routing, and ordering needs FIFO
  • Neither keeps a replayable history like a log
  • A growing backlog can hide a problem for a long time

Trade-offs

ChoiceWe gainWe lose
RabbitMQRouting control, protocols, low latency, can run anywhereOperations work and capacity planning
SQSNo operations, huge scale, pay per useRouting flexibility, and it is tied to AWS
SQS FIFOOrdering per group and deduplicationLower throughput than standard
Long visibility timeoutFewer duplicate runsA crashed job waits longer to be retried
Short visibility timeoutFast retry after a crashSlow jobs run twice at once
Big prefetchHigher throughputUneven work and more messages redelivered after a crash

10Common Problems and Mistakes

Common mistakes

  1. Visibility timeout shorter than the work. The message reappears while a worker is still busy, and the job runs twice.
  2. Acknowledging too early. If the worker acks first and crashes later, the job is lost.
  3. No dead-letter queue. A poison message loops forever and wastes workers.
  4. Assuming order on a standard SQS queue. Standard queues do not promise order.
  5. Non-durable RabbitMQ setup. A restart can drop queues or messages that were never persisted.
  6. Unlimited prefetch. One consumer grabs thousands of messages, and the others sit idle.
  7. Treating a queue as a database. Queues are for passing work, not for storing facts to query.

Things to watch

πŸ“ˆBacklog growth
Depth rising for a long time means workers are too slow or stuck.
⏱️Oldest message age
Shows how late you really are, better than depth alone.
πŸ”Redelivery rate
Many redeliveries point to crashes or a timeout that is too short.
πŸ’ΎRabbitMQ memory and disk alarms
A broker under pressure blocks producers. Watch the alarms.

11Real-World Examples

πŸ›’Checkout flows
An order event is routed to billing, stock and email queues, each handled by its own service.
πŸ–ΌοΈImage processing
Uploads create a message, and a pool of workers makes thumbnails at their own pace.
☁️Serverless on AWS
SQS often triggers cloud functions, with a dead-letter queue for failures.
🏦Back-office systems
RabbitMQ is common where teams need routing rules and several client languages.
πŸ“£SNS plus SQS
One event is published once and copied into several queues, one per consuming service.
πŸ””Notifications
Messages wait in a queue until a sender service pushes them to email or phones.
πŸ“Note
These are typical patterns, not claims about any one company. Product features and limits change, so check the current documentation.
Mini case: SNS fan-out into SQS queues
🧾Order service
→↓publish once
πŸ“£SNS topic
→↓copies
πŸ“¬billing queue
πŸ“¬shipping queue
Producer Fan-out Queues
Each service gets its own queue, so one slow service does not hold back the others.

12Related Topics to Read Next

Message Queues→

The basic idea both products build on.

Message Brokers→

Where RabbitMQ and Kafka fit among brokers.

Event Streaming vs Message Queues→

When a replayable log fits better than a queue.

Dead Letter Queues→

Where failing messages go, in both products.

Delivery Semantics→

Why both give at-least-once and need idempotent workers.

Pub/Sub→

Fan-out with exchanges, or with SNS and SQS.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”RabbitMQ: broker you run. Exchange + bindings route to queues. Pushes to consumers.
  • βœ”SQS: managed queue. Consumers pull. No routing, so use SNS to fan out.
  • βœ”Exchanges: direct (exact), topic (patterns), fanout (all), headers.
  • βœ”Ack late: ack or delete after the work is done, never before.
  • βœ”Visibility timeout: keep it longer than the work, or extend it.
  • βœ”Both are at-least-once: make workers idempotent.
  • βœ”Always: a dead-letter queue and alerts on depth and oldest-message age.
  • βœ”One line: β€œRabbitMQ routes smartly, SQS just runs, and both need you to handle repeats.”
← Previous
Retries with Backoff
Next β†’
Event Streaming vs Message Queues