Queues, async processing & rate limiting
Design background processing and protect services from overload.
By Invicly Tech, , in Interview Preparation. About 13 minutes to read.
In short
Queues let a service accept work quickly and process it later in background workers. Rate limiting protects services from overload by capping how many requests each client can make.
Explained simply
Some work is too slow to do while the user waits: resizing a video, sending a thousand emails, building a monthly report. Instead, the app writes a note saying "this job needs doing" into a queue and answers the user right away. A separate program, a worker, picks up notes from the queue and does the work in the background.
Think of a restaurant. The waiter takes your order, pins the ticket on the kitchen rail and goes back to other tables. The cooks take tickets one by one. If a rush arrives, tickets wait on the rail instead of the waiter freezing.
Queues bring one surprise: a job can arrive twice. If a worker finishes but crashes before saying "done", the queue gives the job to someone else. So workers must be safe to run twice on the same job. That property is called idempotent.
Rate limiting is the other side of protection. It caps how many requests one user or API key may send, such as 100 per minute. Extra requests get a polite "slow down" (HTTP 429), so one noisy client cannot take the service down for everyone.
Press Play on a diagram to walk through it one step at a time.
- Client to API: POST /videos (upload)1POST /videos (upload)
- API to Queue: enqueue transcode job 172enqueue transcode job 17
- API to Client: 202 Accepted, job 173202 Accepted, job 17
- Queue to Worker: deliver job 174deliver job 17
- Worker to Queue: ack after success5ack after success
- Client to API: GET /jobs/17: done6GET /jobs/17: done
- Tokens refill at a fixed rate
- Each request spends one token
- Allows short bursts
- Common for API limits
- Requests queue in a bucket
- Drained at a constant rate
- Smooths bursts out
- Overflow is rejected
- 1Enqueued
API writes the job and returns 202
- 2Attempt 1 fails
Downstream timed out
- 3Backoff and retry
Wait about 1 s, 2 s, 4 s plus jitter
- 4Max attempts reached
For example 5 tries
- 5Dead-letter queue
Alert fires; nothing else is blocked
- 6Fix and replay
Move messages back after the bug is fixed
In depth
Message queue or event log?
Classic message queues such as RabbitMQ and Amazon SQS hand each message to one worker and delete it once the worker acknowledges it. Many workers can share one queue (competing consumers), which spreads work automatically. In SQS a received message becomes invisible for a visibility timeout (30 seconds by default); if the worker does not delete it in time, it reappears for another worker.
An event log such as Apache Kafka keeps messages for a set time, often days, even after they are read. Each consumer group tracks its own position (offset), so several different services can read the same events, and you can replay history after a bug. Kafka keeps order only within a partition, and messages with the same key always go to the same partition, so all events for one order can stay in order.
- Message removed after ack
- Each message to one worker
- Great for background jobs
- No replay once consumed
- Messages kept for a retention period
- Each consumer group has its own offset
- Order kept within a partition
- Replay and many readers
Delivery guarantees, honestly
At-most-once delivery acknowledges a message before processing it: if the worker crashes, the job is lost. At-least-once acknowledges after processing: nothing is lost, but a crash between finishing and acknowledging means the job runs again. Most systems choose at-least-once.
Exactly-once delivery across a network is not possible in general, because the sender can never be sure whether a lost acknowledgement means the work did not happen. What systems offer is exactly-once processing: at-least-once delivery plus deduplication. Kafka transactions and SQS FIFO queues (which drop duplicates sent within a 5-minute window) help, but your own side effects, such as charging a card or sending an email, still need idempotency in your code.
- Queue to Worker 1: Deliver job 17 (now invisible)1Deliver job 17 (now invisible)
- 2Does the workWorker 1 to Worker 1: Does the work
- Worker 1 to Queue: Crashes before the ack3Crashes before the ack
- Queue to Worker 2: Timeout passed: deliver job 17 again4Timeout passed: deliver job 17 again
- Worker 2 to Queue: Does the work again, then acks5Does the work again, then acks
Making workers idempotent
An idempotent worker can see the same message twice and leave the world as if it saw it once. The most common tool is a unique ID per message or job. Record processed IDs in a table with a unique constraint, in the same database transaction as the work itself. If the insert fails because the ID exists, skip the work and acknowledge the message.
Other techniques: write with upserts (insert or update) instead of plain inserts; use conditional updates such as UPDATE orders SET status = 'paid' WHERE id = 7 AND status = 'pending'; and pass an idempotency key to external APIs, as payment providers like Stripe support, so a retried charge is not charged twice. For publishing events reliably, the outbox pattern writes the event into an outbox table in the same transaction as the data change, and a separate relay publishes it to the queue.
- Unique message ID plus a processed table
- Upserts instead of blind inserts
- Conditional updates on the current state
- Idempotency keys for external APIs
- Outbox pattern for reliable events
Retries, backoff and dead letters
Failures are often temporary: a timeout, a database failover, a busy downstream service. Retrying fixes them, but retrying instantly in a tight loop makes an outage worse. Use exponential backoff: wait about 1 s, then 2 s, then 4 s, up to a cap. Add random jitter (pick a random time up to that delay) so a thousand workers do not all retry at the same moment.
Some messages will never succeed, for example because of bad data. These poison messages must not block the queue forever. After a maximum number of attempts, move them to a dead-letter queue (DLQ), raise an alert, and let a person inspect and replay them once fixed. Also watch queue depth and consumer lag: a growing backlog is your signal to add workers or find a slow dependency.
Rate limiting algorithms beyond the buckets
A fixed window counts requests per clock minute. It is simple, but a client can send the full limit at 12:00:59 and again at 12:01:00, getting twice the limit in two seconds. A sliding window log stores each request's timestamp and counts those in the last 60 seconds: exact, but it uses memory per request. A sliding window counter estimates by weighting the previous window's count by how much of it still overlaps, which is cheap and close enough for most APIs.
With many servers, the counters must be shared, usually in Redis, and the check-and-increment must be atomic (one INCR, a MULTI transaction or a Lua script). Reply with 429 Too Many Requests and a Retry-After header. Decide what happens if Redis is down: fail open (allow requests) to protect users, or fail closed to protect the backend.
- One counter per clock window
- Tiny memory
- Allows 2x bursts at the boundary
- Timestamp per request
- Exact count
- Memory grows with traffic
- Two counters, weighted
- Cheap and smooth
- A close estimate, not exact
Learn it in 3 short steps
About 1h each. Track them with a timer in your plan.
- 1Decouple work with message queues~1h
- 2Design idempotent background workers~1h
- 3Compare token bucket and leaky bucket~1h
Key points
- Queues decouple producers from consumers and absorb traffic spikes.
- Most queues deliver at least once, so workers must be idempotent.
- Retry with backoff, then move repeat failures to a dead-letter queue.
- Rate limit per user or API key and return 429 Too Many Requests.
Key terms
Tap a card to flip it. 0/5 known
Examples
import time
class TokenBucket:
def __init__(self, rate, capacity):
self.rate, self.capacity = rate, capacity
self.tokens, self.last = capacity, time.monotonic()
def allow(self):
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False # caller returns HTTP 429A fixed-window rate limiter shared by all servers
Limit: 100 requests per minute per API key. Each request builds a key from the API key and the current minute number, increments it in Redis and sets it to expire after the window. The 101st request in that minute sees a count of 101 and gets 429. Because Redis is shared, it does not matter which app server handles the request. Explain the weakness too: up to 200 requests can pass in the two seconds around a minute boundary; a sliding window fixes that.
import time
import redis
r = redis.Redis()
def allow(api_key, limit=100, window=60):
bucket = int(time.time()) // window # current window number
key = f"rl:{api_key}:{bucket}"
pipe = r.pipeline() # MULTI/EXEC: runs as one unit
pipe.incr(key)
pipe.expire(key, window)
count, _ = pipe.execute()
return count <= limit # False -> reply 429An idempotent "mark order paid" worker
The queue may deliver the "payment succeeded" message twice. Inside one database transaction, the worker inserts the message ID into processed_messages, a table whose primary key is the ID. On the first delivery the insert succeeds and the order is updated. On a duplicate, the insert affects no rows, so the worker skips the update. Only after the transaction commits does the worker acknowledge the message. If it crashes before the ack, the redelivery is harmless.
import psycopg
def handle(msg, conn: psycopg.Connection):
with conn.transaction():
cur = conn.execute(
"INSERT INTO processed_messages (id) VALUES (%s) ON CONFLICT DO NOTHING",
(msg["id"],))
if cur.rowcount == 0:
return # duplicate: the effect was already applied
conn.execute("UPDATE orders SET status = 'paid' WHERE id = %s",
(msg["order_id"],))
# transaction committed: now it is safe to ack the messageQuick reference
- Ack a message only after the work is done; a crash before the ack means redelivery
- SQS visibility timeout defaults to 30 s; set it longer than your slowest job
- Kafka keeps order only within a partition; the same key always goes to the same partition
- Backoff: wait up to base x 2^attempt with random jitter, cap it, then send to a DLQ
- Idempotency: save processed message IDs under a unique key, in the same transaction as the work
- Return 429 Too Many Requests with a Retry-After header
- Fixed windows can let through 2x the limit around a window boundary
- Scale workers on queue depth and consumer lag, not only on CPU
Common mistakes
- Workers that charge or email twice when a message is redelivered.
- Retrying instantly in a tight loop, worsening an outage.
- Rate limiting in each server's memory when traffic is spread across many servers.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Decide synchronous or asynchronous for each, with a reason: checking a login password; sending a welcome email; building a 200-page yearly PDF report; confirming card payment at checkout.
- Exercise 2medium
Write a Python helper that calls a function with up to 5 attempts, using exponential backoff with full jitter and a 30-second cap.
- Exercise 3hard
Implement a single-process sliding window counter limiter: allow(now) returns True if the weighted count of the previous and current windows is under the limit.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use Kafka, RabbitMQ or SQS?
- Use SQS or RabbitMQ for background jobs where each task goes to one worker. Use Kafka when many services need the same stream of events, you need replay, or throughput is very high. On AWS, SQS is the simplest to operate.
- Is exactly-once delivery possible?
- Not in general across a network. Systems give at-least-once delivery plus deduplication, which is called exactly-once processing, and your own side effects still need to be idempotent.
- Where should rate limiting live?
- Usually at the edge, in an API gateway or load balancer, so bad traffic is stopped early. Services can add their own limits too, to protect expensive operations or downstream dependencies.
- What is the difference between rate limiting and load shedding?
- Rate limiting caps each client at a fair share, even when the server is healthy. Load shedding drops or delays requests from everyone when the server itself is overloaded, often replying 503.