Why Use a Message Queue? System Design Explained
A shop wired with direct calls: one outage stops checkout and spikes cascade. How a message queue decouples services, absorbs spikes, and what it costs.
Related chapters
- Start here in System Design
- How a system design interview is graded
- The delivery framework: five phases and a clock
- Numbers to know: what one machine can really do
- System Design Concepts: CAP, SQL vs NoSQL, Message Queues
- SQL vs NoSQL: How to Choose a Database (System Design)
- Traffic Jumps 10×: What Breaks First? (System Design)
- Proxy vs Load Balancer vs API Gateway (System Design)
- CAP Theorem Explained Simply, with Examples
- Message Queue vs Pub/Sub vs Kafka: Differences
- Polling vs Long Polling vs SSE vs Webhooks (System Design)
- API design in System Design
- REST vs GraphQL vs gRPC: Choosing an API (System Design)
- API Goals Canvas: Design APIs from the Consumer
- REST API Design: Resources, Methods, Status Codes
- HTTP Semantics, Richardson Maturity Model and HATEOAS
- GraphQL Explained: Over-fetching, Schema, N+1 Problem
- RPC and gRPC Explained: Protobuf, HTTP/2, When to Use
- API Design Best Practices: 9 Principles with Examples
- API Payload Design: Names, Types, Links and Errors
- Mapping Database Tables to API Resources, Step by Step
- API Design for Complex Schemas: Trees, Polymorphism, Bookings
- API Pagination, Idempotency Keys, Errors and Versioning
- Network-Efficient APIs: HTTP Caching, ETags, Field Selection
- Async APIs: 202 Accepted, Webhooks and Bulk Operations
- API Versioning and Evolution Without Breaking Clients
- API Contracts: OpenAPI, Contract Testing and Docs
- API Security: Authentication, Authorization, Rate Limiting
- OAuth 2, OpenID Connect and Scopes for APIs
- OWASP API Top 10 Explained: BOLA, SSRF and More
- Running APIs: Gateways, Mesh, Rate Limits, Canaries
- API Troubleshooting Interview: Slow APIs and Unexpected Errors
- API Design Review: A Staff-Level Capstone
- Spotify Web API: Resources, IDs, Payloads and Paging
- Spotify Web API: OAuth PKCE, Scopes, Quotas, Rate Limits
- Spotify Web API Changes: Real API Evolution Lessons
- Database-heavy designs in System Design
- Design a Distributed Key-Value Store (System Design Interview)
- Design a Hotel Reservation System (System Design Interview)
- Design a Digital Wallet (System Design Interview)
- Design S3-like Object Storage (System Design Interview)
- Games in System Design
- Shard City: Learn Database Sharding by Playing a Game
- System Design Case Studies: Flash Sale, Chat, ChatGPT
- Flash Sale System Design: Who Gets the Last Item
- Food Delivery App System Design: Which Database?
- Cache Stampede: Why the Database Fell Over and the Fix
- Live Streaming System Design: Scaling for a Final
- ChatGPT System Design: Streaming LLM Responses
- RAG System Design: Product Q&A on Sale Day
- IRCTC Tatkal System Design: Booking Under Extreme Load
- Group Chat System Design: WebSockets and Fan-Out
- Authentication in System Design: Sessions, JWT, OAuth
- Authentication Methods Compared: Sessions, JWT, OAuth
- JWT in System Design: Sessions, Revocation, Refresh Tokens
- JWT Interview Questions and Answers
- Life of a session, step by step
- JWT Structure Explained: Header, Payload, Signature
- Forge lab: why verification must be strict
- JWT vs Session Authentication: Which to Use
- The validation pipeline: where a bad request dies
- How to Revoke a JWT: Blocklists and Short Expiry
- Refresh Tokens and Rotation Explained
- Logout in depth: one device, all devices, SSO
- JWT Security Best Practices
- OAuth 2.0 and OpenID Connect Explained
- Where to Store JWT: localStorage vs HttpOnly Cookie
- JWT in Microservices: API Gateway vs Service Validation
- Microservices, keys, and trust boundaries
- Sender-constrained tokens: making a stolen token useless
- Authentication vs Authorization Middleware
- Failure explorer: what breaks when X fails
- Capacity planner: sessions vs JWT vs hybrid
- Edge cases catalog
- Test it, measure it, migrate to it
- Anti-patterns to reject in a design review
- Design checklist and cheat sheet
Keep learning
Overview
Normal day 100 orders a second Email server down for 12 minutes Sale: 10× orders 1,000 orders a second Add analytics a fifth team wants orders POST /order customer clicks Pay and waits charge card reserve stock send email add loyalty points after every call returned customer waits (the sum of every call) orders failed It works, but the customer waits for the email server. Every service on the chain adds its time to the checkout, even ones the customer does not care about right now. no answer… 5 s timeout 500 error card charged, order rolled back? customer waits, then sees an error orders failed in 12 minutes An email outage became a checkout outage. The other choice, “skip the email if it fails”, loses those emails for good. Nobody remembers to resend them. threads all waiting order service runs out of threads checkout down for everyone orders arriving the slowest service can take The slowest service sets the speed of the whole shop. Waiting calls hold threads and connections. When they run out, healthy services fail too: a cascading failure. NEW: call analytics edit order code, test, redeploy a little slower again 1 change to the order service, for someone else’s feature added to every checkout The order team now owns a list of everyone who cares about orders. Each new listener means a code change, a deploy, and one more thing that can break checkout. customer clicks Pay 120 ms: still a direct call, we need the answer now put “OrderPlaced” in queue 5 ms, saved on disk customer is done stock, email, points each reads the message on its own, within seconds customer waits The customer waits only for what must happen now: the payment. Stock, email and points still happen, a moment later. email worker: down messages wait in the queue email back after 12 min sends the 72,000 waiting emails emails late, none lost The outage stayed inside the email service. The queue remembered the work. Customers got their email a few minutes late instead of a failed checkout. queue grows 800/s email workers still drain 200/s sale ends workers catch up, 100/s faster than new orders checkout stays fast ~80 min The queue absorbed the spike. This is called load levelling. Add email workers to drain faster. The checkout never noticed. analytics subscribes gets its own copy of every OrderPlaced changes to the order service added to checkout Giving each listener its own copy is publish/subscribe. The next chapter shows how brokers do it. What happens today How the shop is wired 2003: direct calls With a message queue Order service Other services Late 1980s A message bus on trading floors Prices had to reach hundreds of desks at once. Publish once, everyone subscribed gets it. IBM MQSeries Queues for banks and airlines: a message survives a crash and arrives exactly once between mainframes. One Java API for queues and topics, so code is not tied to one vendor. ActiveMQ, Amazon SQS, AMQP and RabbitMQ Open source brokers and an open wire protocol. SQS puts a queue behind a web API: no server to run. Amazon SNS Managed publish/subscribe: one message pushed to many queues, functions or URLs. Kafka (LinkedIn) A different idea: an append-only log that keeps messages for days, so readers can replay. system design · core concepts · messaging 1 of 2 Before message queues: why systems needed a mailbox Go back to an online shop around 2003. No SQS, no SNS, no Kafka. Every program that needs another one calls it directly and waits. This chapter shows what broke, how teams patched it, and the idea that fixed it.
1. The world without a queue
A customer pays. The order service must charge the card, reserve stock, send a confirmation email and add loyalty points. It calls each one in turn, like phoning four people and staying on the line until each answers. clicks Pay, waits Order service calls each service in turn A phone call: both sides must be there at the same moment, and the caller waits for the answer. This works on a quiet day. The trouble is that every service in the chain must be up, fast and willing at the same moment.
2. Five problems that kept coming back
One outage takes down everything If the email server is down, the order call fails too. Both sides must be alive at the same time (temporal coupling). The slowest service sets the pace The customer waits for everything Response time is the sum of every call, including work the customer does not need right now. Work is lost on a crash The order service dies after charging the card but before sending the email. Nothing remembers the email was still owed. Every new listener is a code change Analytics, fraud and search all want orders. Each one is another call in the order service, owned by the wrong team. Problem 5 grows fast. With 6 services that each call each other, you can end up with up to 30 one-way links to build, secure and keep running.
3. How teams patched it before brokers were common
Nightly batch files Write the day’s orders to a CSV, FTP it at 2 am, the other system loads it. Nothing is lost, but everything is a day old. A database table as a queue A shared database Let every system read the orders table directly. Now nobody can rename a column without breaking someone else.
4. The idea: a mailbox in the middle
Instead of phoning, leave a letter at the post office. The sender drops it off and leaves. The post office keeps it safe until the receiver collects it, even if the receiver is on holiday. order service “OrderPlaced #812” stores it on disk when the consumer is ready email service Store and forward: the producer only needs the broker to be up, not the consumer. Synchronous call Caller waits. Both sides must be up. Failure travels back to the caller. Asynchronous message Caller continues once the broker has saved it. Consumer works at its own speed. Failure stays on its own side.
5. Lab: the same shop, two ways
Pick what happens today, then switch between direct calls and a queue.
6. How a queue fixes each problem
Problem before What the broker does Name you will hear One outage takes down everything Keeps messages until the consumer is back Decoupling in time, durability The slowest service sets the pace Load levelling, buffering The customer waits for everything Producer returns as soon as the message is saved Asynchronous processing Work is lost on a crash Deletes a message only after the consumer says “done”, otherwise delivers it again Acknowledgement, redelivery A message keeps failing After a few tries, moves it aside for a human to look at Dead-letter queue Every new listener is a code change Publish/subscribe, fan-out The acknowledgement step is what makes a queue safe. Watch a worker crash halfway through: Email worker message #812 deliver #812 marks it “in flight”, keeps a copy in flight start sending email crashes before it finishes no ack before the timeout puts #812 back waiting again worker restarts, gets #812 sends the email, then acks No message is lost. But the email may have gone out twice, which is the price, covered below.
7. What the mailbox costs you
Redelivery means a message can arrive twice. Consumers must be idempotent: doing it twice has the same effect as once. Eventual consistency The order exists before the stock is reserved. The UI must cope with “processing”. Order is not free With several consumers, message 2 can finish before message 1. Keep order only where it matters. A backlog hides problems Nothing errors while the queue quietly grows. Alert on queue depth and the age of the oldest message. One more system to run The broker needs capacity, monitoring and its own failure plan. Harder to debug One request becomes many hops. Carry a correlation id in every message.
8. When not to use a queue
Keep a direct call The caller needs the answer to continue: is the card approved, is the password right, what is the price now. Send a message The work can happen a moment later: emails, thumbnails, search indexing, analytics, notifications. That is why the lab kept the payment as a direct call. A good design mixes both.
9. How we got here
Each step kept the same mailbox idea and changed where the messages live and who keeps track of them. That difference is the next chapter. ★ Remember Direct calls make every service depend on every other being up and fast at the same moment. A broker stores the message, so producer and consumer no longer need to be alive together. Keep a direct call when the caller needs the answer now.
Next
→ Queues, pub/sub and logs: how they differ inside · the outbox pattern · the same job runs twice · Kafka course
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.