System Design · Concept Library · Free article
Async Event Emission: Getting Slow Work Off the Request Path
When one step makes a request slow, the fix is often to stop doing it inside the request: publish a small event to a durable log, return, and let a worker finish later. You protect p99 latency and pay for it with eventual consistency.
When a request got slow because you bolted extra work onto it, the fix is usually not to make that work faster — it’s to stop doing it inside the request. Instead of finishing the slow task before you answer the user, you emit an event — drop a tiny "this happened" message onto a durable queue or log — and return immediately. Something else picks the event up and does the real work in the background, out of the user’s way. The user’s wait collapses to the cost of dropping a message; the heavy lifting still happens, just not on the clock the user is watching. What you trade is immediacy: the result is now eventually consistent (the dashboard trails reality by a moment), and you’ve added a moving part to run and monitor. This page is the principle and the trade-offs; the durable log that makes it work — Kafka — has its own page.
One line on the redirect, and MegaDrop takes the site down
Hatch’s redirect was the fastest thing you owned: a user taps a short link, you look up where it points, you send them there — about 20 milliseconds, done. Then someone asked for click analytics, and you did the obvious thing. Right there on the redirect, just before sending the user on their way, you added one line: bump the click counter in the database. UPDATE links SET clicks = clicks + 1 WHERE id = …. It worked perfectly in testing. It worked in production. It worked right up until a link called MegaDrop went viral.
At fifty thousand taps a second, fifty thousand requests all tried to update the same row at the same time. The database did what databases do to protect a row under concurrent writes — it made them queue up, one behind another, each waiting its turn for a lock. The redirect that took 20 ms started taking five seconds. Users stared at spinning wheels; some just gave up. And here’s the maddening part: nothing was broken. The lookup was fast, the servers were healthy, error rates were zero. You had simply asked a fast read path to also be a slow write path, and under load the slow part dragged the fast part down with it. This page is about the one move that fixes that class of problem — and it’s not "make the write faster."
Don’t do the work — announce that it needs doing
Here’s the move. Instead of doing the slow work before you answer, you emit an event: you drop a tiny message that says "a click happened on MegaDrop" onto a durable queue, and you return the redirect immediately. You don’t wait for anyone to count anything. Somewhere else — a separate worker, on its own schedule — reads that message off the queue and does the real work: updating counts, rolling up totals, whatever analytics needs. The counting still happens. It just doesn’t happen while the user waits.
Notice what changed and what didn’t. The user-facing request went from "look up the link and do a database write under contention" back to "look up the link and drop a message" — and dropping a message onto a log is a handful of milliseconds, no matter how viral the link is. The heavy work didn’t vanish; it moved — off the hot path and onto a background worker that can take its time, batch things up, and never make a single user wait. The word for the two roles is producer (whoever emits the event — here, the redirect) and consumer (whoever processes it later — the analytics worker); the thing in between that holds the events safely is a message queue or, when it’s a retained, replayable one, an event log.
You didn’t make the database faster — you stopped waiting on it
It’s worth being precise about why this works, because the win is not the one people first assume. Emitting an event doesn’t make the counting any faster — the database is doing exactly the same work it did before, maybe more. What changed is that the user’s request no longer depends on that work finishing. The redirect’s response time used to be "lookup + the write, including however long the write had to wait for a lock." Now it’s just "lookup + drop a message." The slow, contended, spiky part has been lifted out of the number the user experiences.
That’s why this is the standard cure for a bad p99 (the near-worst-case latency the unluckiest 1% of users feel — its own idea on the percentiles page). The inline write is exactly the kind of step whose latency explodes under load — fine at low traffic, catastrophic when a hot row gets hammered. Take it off the request and the request’s p99 stops caring how bad the write gets. Drag the traffic up and watch the two approaches diverge: counting inline soars past the latency budget as the write contends, while emitting an event stays flat — because it never touches the counter at all.
The interactive version of this example is available when JavaScript loads.
The thing in the middle has to be durable — or you’re just dropping data
The move only holds up if the thing you emit the event into is trustworthy. If it were just an in-memory list on the web server, a restart would lose every un-processed click, and a burst that outran the worker would overflow and drop events silently — you’d have traded a slow redirect for a lying dashboard. So the middle piece has to do three real jobs: accept events far faster than the consumer can process them (so a viral spike doesn’t block the producer), hold them durably (so a crash on either side loses nothing), and let the consumer read at its own pace (so a slow or restarted worker just catches up later instead of falling over).
That is exactly what a durable log or message queue provides, and it’s why "emit an event" in practice means "append it to something like Kafka" (or a managed queue like SQS, or Kinesis, Pulsar…). The producer and consumer never talk to each other directly — they only talk to the log in the middle, which decouples them: the redirect can keep firing events at full tilt even if the analytics worker is slow, redeploying, or briefly down, because the log is holding the events safely until the worker is ready. See the work move off the request and into the background:
The interactive version of this example is available when JavaScript loads.
Async isn’t free — you trade immediacy for the fast path
It would be dishonest to sell this as a pure win, because it isn’t. The moment you move the counting off the request, the count is no longer up to date the instant the user is redirected — the event is sitting in the log, waiting for the worker to get to it. Your dashboard now trails reality by a moment. That’s eventual consistency: the system will become correct soon, but there’s a window where what you emitted hasn’t been reflected yet. For a click counter that’s completely fine — nobody needs the total to be exact to the millisecond. For other things it would be unacceptable, and knowing the difference is the whole skill.
You also pay in complexity. You’ve added a moving part — the log and the worker — that has to be deployed, monitored, and reasoned about. And debugging gets harder: when something goes wrong, the failure isn’t in the request the user made, it’s "somewhere downstream, later," which is a harder thing to chase. Worst of all, failures can go quiet: the user already got their fast 200 OK and went on with their day, so if the background work later fails, nobody watching the request will ever know. Async trades a slow-but-obvious path for a fast-but-subtle one.
Once work is async, "did it happen exactly once?" gets interesting
The simplest way to emit an event is fire-and-forget: drop it and never look back. Fast, but if the emit itself fails — the network hiccups, the log is briefly unreachable — that event is just gone, and you’ve silently undercounted. So the safer default is at-least-once: the producer keeps trying until it’s sure the event was accepted. That fixes lost events, but it introduces the opposite problem — the event landed, the acknowledgement got lost on the way back, the producer retried, and now the same click is in the log twice. A naive consumer counts it twice.
The instinct is to chase perfect "exactly-once delivery," but that’s expensive and — as the Kafka page explains — doesn’t even extend to side effects outside the log. The robust move instead is to make the consumer idempotent: design the processing so that handling the same event twice lands in exactly the same place as handling it once. For Hatch’s counter, that means counting by a unique click id and ignoring one you’ve already seen, rather than blindly incrementing. Do that, and a duplicate delivery is harmless — you get the effect of exactly-once without the machinery. It’s important enough to have its own page.
The buffer absorbs a spike — but it isn’t a bottomless pit
Here’s the quiet superpower of putting a durable log in the middle: it absorbs bursts. When MegaDrop goes viral, the redirect can fire events far faster than the analytics worker can process them, and nothing breaks — the log simply holds the backlog, and the worker drains it once the spike passes. The producer never has to slow down to match the consumer; the buffer decouples their speeds. That smoothing is exactly why a viral moment doesn’t take the pipeline down.
But a buffer is a shock absorber, not a magic wand, and this is where people get burned. It handles a temporary spike — a burst that drains away afterwards. It cannot fix a sustained deficit: if the consumer is persistently slower than the average rate events arrive, the backlog doesn’t drain, it grows — and grows — until events age out of the log’s retention window and start disappearing silently (that growing gap is consumer lag). A buffer buys you time, not immunity. You still have to provision the consumer to keep up with the average load, and watch the lag. Press play, inject a burst, and watch it drain — then set the produce rate above the consumer’s capacity and watch the backlog climb without bound:
The interactive version of this example is available when JavaScript loads.
One move, a whole family of designs
Once "emit an event, process it later" is in your toolkit, you start seeing it everywhere — it’s one of the load-bearing patterns of large systems:
- Analytics pipelines — the clicks-dashboard chapter itself: emit a click event, and a stream processor rolls it into counts and charts. What reads the log and does that aggregation is the stream-aggregation concept.
- Notifications & emails — emit "user signed up," and a worker sends the welcome email. The signup response doesn’t wait on a mail server.
- The outbox pattern — write your database row and an "event to emit" record in the same transaction, then a separate process ships the event. It guarantees you never commit the change but lose the event (or vice-versa) — the classic fix for "how do I emit reliably?"
- Read models / CQRS — emit domain events and build separate, query-optimised views off them, so reads and writes scale independently.
- Fan-out — emit "post created," and workers push it into each follower’s feed, off the author’s request.
The thing in the middle is always a log or a queue, and the choice between them is the same one the Kafka page lays out: a log (Kafka, Kinesis, Pulsar) is retained, replayable, and readable by many independent consumers — reach for it for event streams, analytics, and anywhere several systems consume the same events. A queue (SQS, RabbitMQ) is simpler, with built-in retries and dead-letter handling — reach for it for straightforward background jobs where one consumer does the work and you don’t need replay.
Pitfalls
- Fire-and-forgetting work that matters. If losing the event is unacceptable, don’t just drop it and hope — use at-least-once delivery (and the outbox pattern to emit reliably).
- No idempotency. At-least-once delivery will redeliver sometimes; a consumer that blindly increments double-counts. Dedupe by a unique id.
- Treating the buffer as infinite. A buffer absorbs a burst, not a sustained deficit. Under-provision the consumer and the backlog grows until events are lost silently.
- Going async when the user needs the result now. Deferring a write the next screen depends on gives a broken, "where did my change go?" experience.
- Hiding failures. The user got a
200before the work ran, so a downstream failure is invisible to them — you need a dead-letter path and alerting, or failures vanish. - Assuming order. Events can arrive out of order or be reprocessed; don’t build logic that assumes strict global ordering unless you’ve deliberately arranged for it.
Best practices
- Defer only what the user doesn’t need synchronously — keep genuinely user-blocking work on the request; push the rest off it.
- Emit into a durable log or queue, never an in-memory list — so a restart or a burst loses nothing.
- At-least-once + idempotent consumers — so events are neither lost nor double-counted.
- Keep events small — a pointer or a compact fact, not a big payload; and keep the emit itself cheap so it doesn’t become the new slow step.
- Monitor consumer lag and add a dead-letter path — alert on a climbing backlog; route poison events aside so one bad message can’t stall the pipeline.
- Design the UI for eventual consistency — optimistic updates, or an honest "counts may lag a moment," rather than pretending the async result is instant.
Rapid-fire cheat-sheet (intern → principal)
- "A database write is slowing down my request — what do you do?"
- If the write is deferrable (the user doesn’t need it done to continue), take it off the request: emit a lightweight event to a durable log/queue and return immediately, and process it on a background worker. The request’s p99 stops depending on the contended write.
- "What do you trade for that?"
- Immediacy. The result is now eventually consistent (a window where the emitted change isn’t reflected), you’ve added a moving part to operate, debugging is harder, and failures can be silent because the user already got a success.
- "How do you avoid losing or double-counting events?"
- At-least-once delivery (retry until accepted, so nothing is lost) plus idempotent processing (handling an event twice equals handling it once, e.g. dedupe by a unique id). Together that’s effectively exactly-once — more robust than chasing exactly-once delivery.
- "What happens under a huge burst?" (senior)
- The durable buffer absorbs it — the producer keeps emitting, the consumer drains the backlog after the spike. But a buffer only handles a temporary burst; if the consumer is persistently slower than the average rate, the backlog grows until events age out and are lost. Watch the lag slope and provision the consumer for the average.
- "When would you NOT make it async?"
- When the user needs the result to continue, on read-after-write (they must immediately see their own change), when strong correctness is required (money, last-seat), or at low volume where the inline work was never a problem and a queue is needless complexity.
- "Log or queue?" (staff)
- A log (Kafka/Kinesis) when you need replay, high throughput, or multiple independent consumers of the same stream. A queue (SQS/RabbitMQ) for simpler background jobs with built-in retries/DLQ and a single consumer. Same principle, different tool.
The takeaway
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.