Async writes: buffering writes with a queue
When traffic spikes beyond what your database can write, requests time out and data is lost. Putting a queue between the API and the database turns that spike into a short backlog. How it works, and what you need to handle when writes become asynchronous.
In one sentence
Instead of writing to the database during the request, the API puts the write in a queue and answers immediately; workers drain the queue at a pace the database can handle.
The problem: spikes
A database can only do so many writes per second. Most of the time you're well below it, but traffic isn't flat: a viral post, a product launch, a TV ad, Black Friday. During the spike, synchronous writes queue up inside the database, latency explodes, connections run out and requests fail.
Trigger a spike in both modes below and compare the failed writes with the queue depth.
How it works
- The API validates the request and publishes a message (
{ type: "view", videoId, userId }) to a queue such as SQS, RabbitMQ or Kafka. - It answers 202 Accepted in a few milliseconds.
- Workers consume the queue and write to the database at a controlled rate, often in batches (one insert of 500 rows instead of 500 inserts).
- If a worker fails, the message is retried; poison messages go to a dead-letter queue.
// API: answer fast
app.post("/views", async (req, res) => {
await queue.send({ videoId: req.body.videoId, at: Date.now() });
res.status(202).end();
});
// Worker: write at the database's pace
for await (const batch of queue.receive({ max: 500 })) {
await db.views.insertMany(batch);
await queue.ack(batch);
}What changes when writes are async
- Eventual consistency: the write isn't in the database yet when the user gets the response. Show it optimistically in the UI, or don't promise immediate visibility.
- Idempotency: queues deliver at least once, so the same message can be processed twice. Use an idempotency key or upserts so duplicates are harmless.
- Ordering: standard queues may reorder messages. Use FIFO queues or partition by key (per user, per order) when order matters.
- Monitoring: watch the queue depth and the age of the oldest message. A queue that keeps growing means workers can't keep up: add workers or optimize writes.
- Errors are reported later: validate as much as possible before enqueuing, and notify the user if processing fails.
When to use it
Great for
- View counts, likes, analytics and logs
- Sending emails and notifications
- Importing files, processing uploads
- Any write where a few seconds of delay is fine
Keep synchronous
- Payments and anything the user must see confirmed now
- Writes that must fail immediately if invalid ("username already taken")
- Very low traffic, where a queue only adds moving parts
Key takeaways
- 01A queue between the API and the database turns traffic spikes into a temporary backlog instead of errors.
- 02The API answers 202 Accepted; workers write at the database's safe pace, ideally in batches.
- 03Async writes bring eventual consistency, duplicates and ordering to handle: make consumers idempotent.
- 04Monitor queue depth and message age to know when to add workers.
Check your understanding
1 of 3
With async writes, what does the API do during the request?
Related concepts
SQS vs SNS
SQS stores messages until one consumer pulls and processes each of them; SNS pushes each message to every subscriber immediately and doesn't store it.
8 min read →Read-heavy vs write-heavy
A read-heavy part is read far more than it changes (a video page); a write-heavy part receives a constant flood of new data (view counts, analytics). Each one needs different tools.
7 min read →AWS Lambda
AWS Lambda runs a function only when an event arrives, scales to many copies by itself and bills per millisecond, but each run is capped at 10 GB of memory and 15 minutes.
8 min read →Idempotency & retries
An operation is idempotent if doing it twice has the same effect as doing it once. With an idempotency key, the server recognizes a retry and returns the original result instead of charging, booking or sending again.
6 min read →