12. Queues & Async Processing

Where this fits: Not every task must finish before you respond to the user. Queues let your API say "got it!" quickly while workers handle the slow stuff in the background โ€” like a restaurant kitchen ticket system.


Learning goals

By the end of this lesson, you should be able to:

  • Explain sync vs async processing using the restaurant kitchen ticket analogy
  • Draw producers, queues, and consumers in an HLD diagram
  • List why queues help (spike absorption, decoupling, retries, parallelism)
  • Understand at-least-once delivery and why idempotency is mandatory
  • Describe dead-letter queues (DLQ) and poison message handling
  • Compare ordering guarantees: global vs per-key
  • Distinguish task queues (SQS/RabbitMQ) vs event logs (Kafka)
  • Map common product features to queue-based workflows

The restaurant analogy โ€” why async exists

Imagine a sit-down restaurant:

Synchronous (bad kitchen model)

You order pasta.
Waiter stands at your table.
Waiter walks to kitchen, cooks pasta, plates it, returns.
You stare at waiter for 20 minutes.
No other tables get served.

This is like an HTTP request that blocks until virus scan + thumbnail generation + ML tagging + email notification all complete.

Asynchronous (real kitchen model)

You order pasta.
Waiter writes ticket #47, pins it to kitchen rail, brings bread immediately.
You chat, drink water โ€” not blocked.
Kitchen cooks when ready; runner delivers pasta when done.

This is async processing:

  1. API accepts the request quickly
  2. Enqueues work (ticket)
  3. Returns 202 Accepted or success with "processing"
  4. Workers consume jobs in the background

Everyday mapping:

RestaurantSystem
Customer orderHTTP request
WaiterAPI server
Ticket on railMessage in queue
CooksWorker processes
Dish windowDatabase / email / push service
"Your table's food is up!"Webhook, push notification, or poll status

Sync vs async โ€” when to use which

Synchronous โ€” user waits for result

POST /login
  โ†’ verify password
  โ†’ create session
  โ†’ return token

User NEEDS the token to proceed โ€” must be sync.

Use sync when:

  • User immediately needs the result to continue
  • Operation is fast (< 200โ€“300 ms typical UX budget)
  • Strong consistency required in the response (account balance display)
  • Failure must be shown right now (payment declined)

Asynchronous โ€” user can wait or get notified later

POST /photos/upload
  โ†’ store raw file in S3
  โ†’ enqueue { photo_id, user_id, sizes: [thumb, medium, large] }
  โ†’ return 202 { "status": "processing", "photo_id": "abc" }

Background workers:
  โ†’ resize images
  โ†’ run moderation ML
  โ†’ update DB with URLs
  โ†’ push notification "Your photo is ready"

Use async when:

  • Work is slow (seconds to minutes)
  • Work can fail and retry without user staring at spinner
  • Spiky traffic โ€” queue absorbs bursts
  • Multiple downstream services must react to same event
  • User doesn't need result in the same HTTP response

Core components

ComponentRoleExample
ProducerSends messages/jobsAPI server after upload
Queue / TopicDurable bufferSQS, RabbitMQ, Kafka
Consumer / WorkerProcesses messagesthumbnail-worker pod
BrokerSoftware managing the queueRabbitMQ server, Kafka cluster

Why queues help โ€” four superpowers

1. Smooth traffic spikes

Black Friday: 50,000 orders in 1 minute

Without queue: API tries to send 50k emails inline โ†’ timeouts, crashes
With queue:    API enqueues 50k jobs in seconds โ†’ workers drain at steady rate

Everyday analogy: Ticket rail holds orders during rush hour; kitchen processes at its pace, not the dinner rush pace.

2. Decouple services

Order service โ†’ publishes order.created
                โ†˜ Email service listens
                โ†˜ Inventory service listens
                โ†˜ Analytics service listens

Order service doesn't call email API directly โ€” fewer cascading failures

3. Retries without failing the user

User uploads photo โ†’ API returns success
Worker tries ML moderation โ†’ external API timeout
Worker retries with backoff (1s, 2s, 4s...) โ†’ eventually succeeds

User already got "upload accepted" โ€” no spinner of death

4. Parallelism

One queue, ten workers โ†’ ten jobs processed concurrently
Scale workers horizontally without changing API

Delivery guarantees โ€” what "done" means

GuaranteeMeaningTypical use
At-most-onceMessage delivered 0 or 1 time; may lose messagesMetrics where loss OK
At-least-onceMessage delivered 1+ times; duplicates possibleMost common (SQS, RabbitMQ default)
Exactly-onceProcessed once and only onceHard; often simulated with idempotency

Beginner reality: Assume at-least-once. Plan for duplicates from day one.


Idempotency โ€” handling duplicates safely

An operation is idempotent if doing it twice has the same effect as doing it once.

def process_thumbnail_job(job):
    photo_id = job["photo_id"]

    # Idempotency check
    if db.job_already_completed(photo_id, "thumbnail"):
        return  # safe no-op on duplicate

    image = s3.download(job["s3_key"])
    thumb = resize(image, 200, 200)
    s3.upload(f"thumbs/{photo_id}.jpg", thumb)
    db.mark_job_completed(photo_id, "thumbnail")

Idempotency patterns

PatternHow
Natural idempotencySET status = 'shipped' WHERE id = 5 โ€” same result twice
Idempotency key tableStore job_id or message_id after success
Upsert by unique keyINSERT ... ON CONFLICT DO NOTHING
Version / state machineOnly transition pending โ†’ processing โ†’ done if valid

Everyday analogy: Paying a bill online with confirmation #8821. If you click "Pay" twice, the bank checks confirmation #8821 already processed โ€” second click doesn't double-charge.

Where to store idempotency keys

Option A: DB table (job_id PRIMARY KEY, status, completed_at)
Option B: Redis SET with TTL (fast dedup window)
Option C: SQS deduplication ID (FIFO queues, 5-min window)

Poison messages and dead-letter queues (DLQ)

A poison message is a job that always fails โ€” malformed payload, bug in code, missing foreign key.

Job: { "photo_id": "xyz", "format": "webp" }
Error: WebP codec not installed โ†’ fail โ†’ retry โ†’ fail โ†’ retry โ†’ โˆž

Without handling, poison messages block the queue or waste infinite retries.

Solution: max retries + DLQ

SQS example:
  maxReceiveCount = 3
  deadLetterTargetArn = arn:...:my-dlq

After 3 failed processing attempts โ†’ message moves to DLQ
Alert on DLQ depth > 0
Engineer fixes bug, replays messages

Everyday analogy: Kitchen ticket for "allergic to everything burger" โ€” impossible order. After 3 failed attempts, ticket goes to manager's desk (DLQ) instead of clogging the line forever.


Ordering โ€” global vs per-key

Global ordering โ€” expensive

All events worldwide processed in exact order: E1, E2, E3, ...
Requires single consumer or heavy coordination โ†’ bottleneck

Per-key (partition) ordering โ€” common and practical

All events for conversation_id = 99 processed in order
Events for conversation_id = 100 independent

Kafka: messages with same partition key โ†’ same partition โ†’ ordered within partition
NeedApproach
Chat messages in one threadPartition by conversation_id
User account eventsPartition by user_id
Global analyticsOrdering often not required

Trade-off: Strict ordering within a key limits parallelism for that key โ€” one consumer per partition at a time.


Task queue vs event log (Kafka)

Beginners confuse these โ€” they're different tools for overlapping problems.

Task queue โ€” "do this job"

Examples: Amazon SQS, RabbitMQ, Celery, Sidekiq, Google Cloud Tasks

Producer:  "Please send email to alice@example.com"
Queue:     One consumer typically processes message โ†’ deletes it
Model:     Work queue โ€” job done, message gone

Best for:

  • Background jobs (email, thumbnails, PDF generation)
  • Task distribution among workers
  • Retry + DLQ per job

Event log (stream) โ€” "this fact happened"

Examples: Apache Kafka, Amazon Kinesis, Google Pub/Sub (hybrid), Redpanda

Producer:  "order.created { order_id: 42, ... }"
Log:       Message appended to topic; retained for days/weeks
Consumers: Many independent consumer groups read same stream
Model:     Immutable ledger of events

Best for:

  • Event sourcing patterns
  • Multiple services reacting to same event
  • High-throughput analytics pipelines
  • Replay history ("reprocess last 7 days")

Comparison table

Task QueueEvent Log (Kafka)
Message lifecycleDeleted after processingRetained by policy
ConsumersUsually one worker per messageMany consumer groups
ReplayHard / noYes โ€” re-read offset
OrderingPer queue (FIFO options)Per partition
Mental modelTo-do listNewspaper archive
ComplexityLowerHigher (partitions, offsets, rebalance)

Beginner advice: Start with a task queue (SQS + workers). Adopt Kafka when you need multiple consumers, replay, or very high throughput event streams.


Common queue products (quick reference)

ProductTypeNotes
Amazon SQSTask queueFully managed, simple, at-least-once
RabbitMQTask queueFlexible routing, exchanges
Redis Streams / BullLightweight queueGood for smaller apps; durability caveats
Celery + Redis/RabbitPython task frameworkPopular in Django/Flask
SidekiqRuby task frameworkRedis-backed
Apache KafkaEvent logPartitions, consumer groups, replay
Google Pub/SubHybridPush/pull, multiple subscribers
AWS EventBridgeEvent busServerless routing rules

Example use cases โ€” feature to job mapping

Product featureQueue message / eventWhy async
Welcome email on signup{ "type": "send_email", "template": "welcome", "user_id": 42 }SMTP slow; retries needed
Image thumbnail{ "photo_id": "abc", "sizes": [64, 256, 1024] }CPU-heavy resize
Feed fanout{ "post_id": 99, "author_id": 7, "follower_ids": [...] }Millions of followers โ€” can't inline
Search index update{ "event": "document.updated", "id": "prod_8812" }Elasticsearch bulk indexing
Push notification{ "user_id": 42, "title": "...", "body": "..." }FCM/APNs rate limits
PDF invoice generation{ "order_id": 1001 }Slow; retry on failure
Analytics tracking{ "event": "page_view", "url": "/shoes", "ts": "..." }Fire-and-forget; huge volume
Fraud check{ "payment_id": "pay_xyz", "amount_cents": 5000 }External API; don't block checkout ACK
Video transcoding{ "video_id": "v1", "formats": ["720p", "1080p"] }Minutes of processing
Delete user (GDPR){ "user_id": 42, "cascade": true }Many tables/services to clean

End-to-end HLD pattern (you'll redraw often)

Sync path:  Client โ†’ API โ†’ DB โ†’ response (fast CRUD)
Async path: Client โ†’ API โ†’ DB (minimal) + Queue โ†’ Workers โ†’ side effects

Upload photo โ€” sequence diagram


Backpressure and worker scaling

Queue depth growing?  โ†’ Add more workers (scale consumers)
Queue always empty?   โ†’ Maybe over-provisioned workers
Processing lag > SLA? โ†’ Scale workers or optimize job handler
MetricMeaning
Queue depthJobs waiting โ€” backlog size
Age of oldest messageHow far behind you are
Processing rateJobs/sec consumed
Error rate / DLQ depthPoison messages or bugs

Autoscaling rule (conceptual): If queue depth > 1000 for 5 min โ†’ add worker instances.


Common mistakes

MistakeConsequenceFix
Non-idempotent consumersDuplicate emails, double chargesIdempotency keys
No DLQPoison message blocks queue forevermax retries โ†’ DLQ + alerts
Async without status trackingUser doesn't know when doneJob status table + poll/webhook
Putting huge payloads in queueBroker bloat, slowStore in S3; queue only reference ID
Sync call chain instead of queueCascading failuresPublish event; let consumers react
Kafka for simple emailsOver-engineeringSQS is enough
Ignoring ordering needsChat messages shuffledPartition by conversation_id
No visibility timeout tuningMessage reprocessed while still runningExtend heartbeat / adjust timeout

Interview phrases that sound solid

  • "Upload returns 202 immediately; thumbnail generation runs on SQS with idempotent workers keyed by photo_id."
  • "Failed jobs retry 3 times with exponential backoff, then land in a DLQ for ops review."
  • "Chat messages publish to Kafka partitioned by conversation_id for per-thread ordering."
  • "Feed fanout is async โ€” posting completes in 50ms; followers' timelines update via background workers."

Check your understanding

Questions

  1. Explain async processing using the restaurant ticket analogy.
  2. Why shouldn't thumbnail generation run inside the upload HTTP request?
  3. What is at-least-once delivery, and what must consumers do about it?
  4. Write pseudocode for an idempotent email-sending worker.
  5. What is a dead-letter queue for?
  6. When do you need per-key ordering vs global ordering?
  7. What's the main difference between SQS (task queue) and Kafka (event log)?
  8. Name three product features that should be async and one that should stay sync.

Answers

Click to reveal answers
  1. Waiter (API) takes order, writes ticket (enqueue), brings bread (quick response). Kitchen (workers) cooks when ready. Customer isn't blocked while food prepares.

  2. Thumbnail generation is slow and CPU-heavy (seconds). Blocking the HTTP request causes timeouts, poor UX, and can't scale independently. User only needs "upload accepted" immediately.

  3. At-least-once means a message may be delivered more than once (retries after crash). Consumers must be idempotent โ€” processing twice must not double-charge, double-email, etc.

  4. def send_email_job(job):
        msg_id = job["message_id"]
        if db.already_sent(msg_id):
            return
        smtp.send(job["to"], job["body"])
        db.mark_sent(msg_id)
    
  5. DLQ holds messages that failed repeatedly (poison messages) so they don't block the main queue. Engineers inspect, fix bugs, and replay.

  6. Per-key ordering when related events must stay ordered (chat in one conversation) but unrelated keys can parallelize. Global ordering when entire system needs strict sequence โ€” rare and expensive.

  7. SQS: job queue โ€” one consumer typically processes and deletes message. Kafka: append-only log โ€” many consumer groups, retention, replay, partition-based ordering.

  8. Async: thumbnails, welcome email, feed fanout. Sync: login (need token now), payment authorization response, real-time password verification.


Quick reference card

Sync         โ†’ user waits; fast; result needed now
Async        โ†’ enqueue ticket; workers process later
At-least-once โ†’ duplicates happen โ†’ idempotency required
DLQ          โ†’ poison messages after max retries
Ordering     โ†’ per-key (conversation_id) not global
Task queue   โ†’ do this job (SQS, RabbitMQ)
Event log    โ†’ fact happened (Kafka) โ€” replay, multi-consumer
HLD pattern  โ†’ API โ†’ DB + Queue โ†’ Workers โ†’ side effects

Next: 13. CDN & Object Storage โ€” caching at the edge for static files and media.