Skip to content
AKRAmit Kumar Raikwar
All notes
3 min read

Redirect first, record after

Analytics should never sit in the critical path of a redirect. A note on ordering writes behind responses.

ArchitecturePerformance

When I built DevLink, I wrote the obvious version of a link shortener first: look up the link, write an analytics row, then issue the redirect. It flies on your own machine against a local database. It falls apart the day that analytics write turns out to be slower than you assumed.

You have put a write on the critical path of somebody else's click. Every millisecond the insert takes is a millisecond they spend waiting, and they are waiting on information you do not need in order to answer them.

Invert the order

The lookup has to come first, since you cannot redirect without knowing where to. The recording does not. Send the response, then persist the event.

const target = await resolve(slug)
if (!target) return notFound()

// respond immediately
queueClickEvent({ slug, referrer, country, at: now })
return redirect(target)

The redirect now costs one read. The write sits on a queue where it can be slow, retried or batched and nobody waiting on a browser tab will ever know.

What you trade away

Guaranteed capture. If the process dies between responding and persisting, that click is gone. For click counts nobody audits, that is a cheap trade. For a payment or anything that touches money it is not, and this pattern has no business there.

Ask whether the write has to be durable before the response, or only eventually. Most of the time it is eventually, and that answer buys you latency for free.

The same shape elsewhere

This travels further than redirects. In Edgvance, order confirmation emails, invoice generation and inventory reconciliation all run on BullMQ instead of inline in the checkout handler. A slow email provider cannot hold a checkout response open, because the checkout never waits for it.

The question to put to any handler: what in here does the caller need before I can answer them? Usually less than what is sitting in there now.

Written by Amit Kumar Raikwar, full-stack engineer & product designer in Indore, India.