In this article
November 24, 2026
November 24, 2026

Scaling events and webhooks: from sync to async, in order

Why event ordering is easy in one database and hard across two, and the trade-offs we made at WorkOS to keep ordering when event capture went asynchronous.

Explore with AI
Open in ChatGPT
Open in Claude
Open in Perplexity

We moved event capture at WorkOS from synchronous to asynchronous to keep up with volume. This is what we learned doing it: why ordering is easy in one database and hard across two, how an SQS standard queue, an SQS FIFO queue and the size of a message group each shaped the design, which trade-offs we made on purpose, and the pipeline we ended up with.

The promise, and why it used to be easy

An event is a record that something happened, such as dsync.user.created, connection.activated or organization.updated, and it carries the full object it describes. You get events two ways: webhooks push them to your endpoint as they happen, at-least-once, no order on receipt; the Events API is a log you pull with a cursor: every event, once, replayable for 90 days.

For a long time the Events API also promised a consistent order, and it was easy: events were written in the request, synchronously, as the change happened. One write followed another, so order came for free. Customers built on it.

Scale needs async

Events grow without bound; the Events API is a scan-shaped read and webhook fan-out is a read on every write. All of it competed with the core write path for one database. So events moved to their own database.

That created the problem this post is about: a request now writes to two databases, and no transaction spans them. Write both and one can fail: a change with no event, or an event for a change that rolled back. The shape we landed on is to write the event into an outbox table in the core database, in the same transaction as the change, and let a pipeline carry it to the events database afterwards.

An API request writes the user row and an event_outbox row in one core-database transaction; a pipeline carries the outbox row to the events database afterwards.

The outbox makes the event exactly as reliable as the change. It also makes capture asynchronous by construction. And async is where order goes to die: a pipeline delivers late, in parallel, and sometimes twice.

The design we ended up with

Before the iterations, here is where they landed. The outbox row leaves the core database through change data capture (CDC), in commit order, onto a stream. The stream feeds a set of SQS FIFO queues, one per traffic shape. A capture worker takes each message, writes the event to the events database, and creates one delivery per webhook endpoint. One key, computed when the outbox row is written, decides the stream partition, the queue’s message group, and which worker handles it.

The capture pipeline: outbox table, CDC in commit order, a Kinesis stream and SQS FIFO queues keyed by one group key, an idempotent capture worker that writes the events database.

Every hop is at-least-once. The worker is idempotent: it claims the event id before writing, and a duplicate from any hop finds the claim and stops. So the hops above it are allowed to redeliver, and a slow hop costs latency, not loss.

How the design got here

SQS standard queue first. The first version used an SQS standard queue, and it is the better queue on every axis but one:

  • Throughput scales with the consumers you add.
  • Any worker takes the next message, so a burst spreads across the pool.
  • Nothing is serialized, so nothing is blocked.
  • Fairness comes free: a standard queue spots a noisy neighbour by its message group id and serves the quiet tenants first.

What it doesn’t do is order. Under retries and parallel consumers it reorders exactly the pairs customers depend on: a membership before its user, a delete before an update. That is not a weaker version of the promise, it’s the opposite of it. So we moved to an SQS FIFO queue, and the trade is the mirror image:

SQS standard queueSQS FIFO queue
throughputscales with consumers, no ceilinga per-queue ceiling, and one consumer per message group at a time
fairnessbuilt in — a noisy neighbour is detected by its message group id, quiet tenants go firstgone — the group id now means order, not tenant, so nothing detects a noisy neighbour; a producer that enqueues fifty thousand messages is ahead of whoever arrives next
ordernone; reorders under retryper message group, guaranteed, across retries

Message groups have to be small. An SQS FIFO queue orders within a message group, and a group is processed by one consumer, one message at a time, each with a database write. That is on the order of fifteen events per second for that group, however many workers you run. The size of the group decides everything:

Three rejected message-group sizes (one global, one per environment, one per object) and the chosen one, the dependency root: the smallest object whose events must stay in order.

So we asked the only question that matters: what do consumers actually need in order? The answer is an object’s own history. Think of every object as having its own timeline: a user’s created → updated → deleted, a group’s, a directory’s. A consumer needs each timeline in order; across timelines it needs nothing. We call the object that owns a timeline the event’s dependency root: the smallest object whose events a consumer must see in sequence. Every outbox row gets a message_group_id from it, and that one key is used at every hop: the stream partition, the message group, the worker.

ruleevents → key
the object’s own lifecycleuser.* → user:<id> · organization.* → org:<id> · dsync.group.* → dgroup:<id> · connection.*, role.* → obj:<id>
events about a user that aren’t user eventssession.*, organization_membership.*, authentication.* → user:<user_id>
two parentsdsync.group.user_added / user_removed → the user, not the group
nothing is ordered after thesereads, failed attempts with no user → a unique key per row

Two rules inside that table carry the trade-offs.

A membership sits on two timelines, and we could keep it on only one. dsync.group.user_added involves a user and a group, and a row has one key. We key it by the user. Users are created, changed and removed far more often than groups, so the user key spreads the load and keeps the busy stream in order. The group key would be a hot key: add ten thousand users to one group and you are back to one group processed one at a time. The trade-off, stated plainly: we protect the order of the frequent pair and give up the rare one. dsync.group.created and dsync.group.user_added for the same group are on different keys and can arrive in either order. We accept that.

No key where nothing depends on it. A read event is a fact about a moment; giving it a real key serializes it behind unrelated reads for no benefit. Each gets a unique key and runs at full parallelism. The cheapest ordering guarantee is the one you don’t make.

One key, three hops. Each hop keeps order only inside its own unit: the shard, the message group, the worker’s current group. The unit has to be the same object all the way down: partition the stream by one key and group the queue by another, and one group’s records arrive from two shards, each in order, together in neither. The key is computed once, when the outbox row is written, and every hop reads the same column.

Fairness is ours to handle now. The FIFO queue took away the free fairness of the standard queue, so we put some back: several queues instead of one, split by traffic shape: steady application events in one, large bursty producers like a directory sync in another, non-production environments in their own. A bulk sync fills its own queue’s budget and its own groups; a login event never queues behind it. Related events always share a key, so they always share a queue; across queues no order is needed.

The risks we accept, explicitly

the risk we acceptwhat bounds it
no order across unrelated objectsthe Events API orders by capture; every event carries its occurrence timestamp for consumers who need sequence
group creation and group membership can arrive in either orderthe membership names the group; a group you have not seen is one API fetch away
one object’s throughput is one worker’s write latencyan object producing faster than that lags; it can’t be spread without breaking its own order. Lag, not loss — the stream and queues hold records for days, and the only terminal state is a dead-letter queue with an alarm on it
fairness between tenants is our job, not the queue’sseparate queues isolate traffic shapes; within one, a hot group holds its own place in line
every hop is at-least-oncethe idempotent writer makes a duplicate anywhere a no-op; the same property lets a fallback poller read the outbox table directly when CDC is paused for maintenance, and the overlap is harmless
an event appears a moment after the change, not in itthe price of leaving the request path

What changes for you

The Events API orders by when we captured an event, and your cursor is durable, so you never miss one. Each object has its own timeline, and events on one timeline are in the order they happened. Across timelines they may not be (a group and one of its memberships, say), so take the payload as the truth, not the arrival order. Webhooks are unchanged: at-least-once, with retries, upsert from the full payload and tolerate out-of-order receipt.

Concretely, these are the pairs that can cross today: two events a consumer might expect in sequence that sit on different keys. The list is as of writing; new events get a key under the same rule, and the rule, not the list, is the promise.

usually first → thenwhy they can arrive in either order
dsync.group.created → dsync.group.user_added, and dsync.group.user_removed → dsync.group.deletedthe membership is keyed by the user; the group by itself
dsync.activated → any dsync.user.* / dsync.group.*, and dsync.user.deleted → dsync.deletedthe directory is one root; each of its users and groups is another
organization.created → organization_membership.created, and organization_membership.deleted → organization.deletedthe membership is keyed by the user
organization.created → organization_domain.created · connection.activated · organization_role.createdeach of those objects is its own root
invitation.accepted → user.created · organization_membership.createdthe invitation is one root; the user it creates is another
user.created → group.member_added, and group.member_removed → user.deleteda group membership is keyed by the group
role.created → organization_membership.updated, and permission.created → role.updatedthe role, the permission and the membership are three roots
authentication.sso_started → authentication.sso_succeededthere is no user yet when SSO starts, so the start is keyed by the SSO session; success is keyed by the user
vault.kek.created → vault.data.createdthe key and the data under it are separate roots

Every pair above is a parent and a child, or two siblings, whose payloads carry what the other side needs. Upsert from the payload, and each row is a non-event. The membership rows get one extra step, because a membership can name a group you have never seen:

  • The group is already in your database: apply the membership from the payload.
  • The group is unknown: fetch it from the API first. The event exists because the change already happened, so the group is there, as it is now.
  • The fetch returns 404: the group was deleted in the seconds since. Drop the event.
  • Never create the group from the membership payload: that can resurrect a group deleted a moment earlier.
on dsync.group.user_added:
  group = db.get(event.data.group.id)
  if group is None:
    res = GET /directory_groups/{event.data.group.id}
    if res.status == 404: return      # deleted since; nothing to apply
    group = db.create(res.body)       # the group as it is now
  db.add_member(group, event.data.user)

One fetch per group you meet out of order is the whole cost.

What changed underneath is what we can promise ourselves: an object’s history is captured in order, a duplicate anywhere is harmless, and a slow minute is a slow minute and nothing more. One object, one key, three hops — that is most of how we got there.