# When should a write go through a queue instead of the API?

By Vishal Kumar · Published 2026-11-02 · Updated 2026-11-13
Source: https://fungyaan.com/p/queue-vs-api-writes
Tags: system-design, queues, reliability, postgres, sqs

**The verdict, which the evidence below will earn:** put the work behind a write on a queue when it's slow, depends on something unreliable, or can finish after you've answered the user, such as emails, syncs to other systems or heavy processing. Keep it synchronous when the caller needs the result before they can continue, like a payment authorisation or "is this username free?". And never send to the queue directly from the request handler: write the message to an *outbox* table in the same database transaction as the data, so a crash can neither lose an event nor send one for data that was rolled back.

> **Case file**
>
> | | |
> |---|---|
> | **The case** | A confirmation email never arrives, or arrives for an order that doesn't exist |
> | **Suspects** | Do it all in the request, publish to the queue from the request |
> | **Culprit** | A dual write: database commit and queue send with no shared transaction |
> | **The fix** | Outbox row in the same transaction, a relay, an idempotent consumer |
> | **Evidence** | multi-tenant-event-driven-ref, k6 against docker compose with LocalStack |

## The case

An order is placed, the customer sees "thank you", and the confirmation email never arrives. Or worse: an email arrives for an order that, according to the database, never existed. Somewhere between the database and the queue, an event went missing or appeared from nowhere.

The fix, when we get to it, is one of my favourite patterns in backend engineering. The outbox takes a problem that sounds like it needs distributed transactions and solves it with the transaction you already have, one extra table and a small relay. The [consistency case](/p/consistency-without-2pc) compares it with the alternatives.

The rest of this case compares the three ways to handle a write, walks through four scenes, and shows the code and load-test numbers from a reference project, [multi-tenant-event-driven-ref](https://github.com/the-vishal-kumar/multi-tenant-event-driven-ref). Its API takes orders, and a Go worker confirms them from Amazon SQS.

## The three suspects

| | Synchronous: do it all in the request | Publish to the queue from the request | Outbox, then queue |
|---|---|---|---|
| **What it fixes** | Nothing to fix: simplest, and the caller gets the final result | Slow or flaky work leaves the request path | Same, and the data and the event can't disagree |
| **What it costs** | Latency and availability of every dependency add up in your API | Two writes to two systems with no transaction across them | An extra table, a relay process, and consumers that must ignore duplicates |
| **How it fails** | One slow dependency times out your whole endpoint; retries hit it again | Crash after the database commit: the event is lost. Send before the commit and then roll back: an event for data that doesn't exist | Delivered at least once: duplicates are normal, so every consumer must dedupe |
| **Pick it when** | The caller needs the outcome now, and the work is fast and local | Rarely: only if losing an event or a phantom event is acceptable (e.g. best-effort analytics) | Anything that must happen exactly once *in effect*: emails, syncs, fulfilment |
| **Avoid it when** | Any step calls a third party or takes more than a few hundred ms | Business events | The caller needs the result synchronously |

The middle column is the one teams build by accident, and it's our prime suspect: `INSERT order; await sqs.send(...)`. It works in every demo and breaks in production. The [design note](https://github.com/the-vishal-kumar/multi-tenant-event-driven-ref/blob/main/docs/adr/0002-queue-semantics.md) calls it a dual write: two systems, no shared transaction, and a crash window between them. That window is where events vanish.

## Four scenes

**1. Order confirmation email → queue (outbox).** The user doesn't need the email before seeing "order placed". The email provider is a third party that can be slow or down. If you send it inside the request, a provider outage becomes your outage. Put an `order.created` event in the outbox, and have a worker send the email with retries.

**2. Sync to a slow third-party ERP → queue (outbox), with a dead-letter queue.** ERP APIs are often slow, rate-limited and occasionally reject data. A synchronous call makes your API as slow as the ERP. Queue it, retry with backoff, and dead-letter messages that keep failing with the *reason* attached, so someone can fix the data and replay them.

**3. Absorbing traffic spikes → queue.** If the expensive part of a write can lag a little, a queue lets the API keep answering quickly while the backlog drains. The load test below shows exactly this.

**4. Payment authorisation → synchronous.** The customer is waiting to know whether the card was accepted, and the next screen depends on it. Do it in the request, with an idempotency key so a retried request can't charge twice. *Capturing* the payment or sending the receipt later can then go through the queue.

A quick interrogation for any write: **"Can I answer the user before this finishes, and is it OK if it happens twice?"** If it can wait, queue it. If it can't be allowed to happen twice, make the consumer idempotent, because a queue will eventually deliver it twice.

## The reveal: how the reference project does it

Here's how the pieces fit together in real code, and why each one closes a gap.

```mermaid
sequenceDiagram
  participant API
  participant DB as PostgreSQL
  participant R as Relay
  participant Q as SQS
  participant W as Go worker
  API->>DB: one transaction: INSERT order + outbox row
  R->>DB: claim unpublished rows (FOR UPDATE SKIP LOCKED)
  R->>Q: send batch
  R->>DB: mark published
  Q->>W: deliver (at least once)
  W->>DB: one transaction: record event_id + confirm order
  Note over W,DB: a duplicate hits the primary key and changes nothing
```

### 1. The data and the event commit together

The API inserts the order and its outbox row in **one transaction**. There's no window left for an event to slip through. An `Idempotency-Key` header makes client retries safe: `UNIQUE (tenant_id, idempotency_key)` plus `ON CONFLICT DO NOTHING` means a retried request returns the original order instead of creating a second one. From [`api/src/orders.ts`](https://github.com/the-vishal-kumar/multi-tenant-event-driven-ref/blob/main/api/src/orders.ts), trimmed:

```ts
const inserted = await c.query<Order>(
  `INSERT INTO orders (tenant_id, idempotency_key, request_hash, currency, total_cents, items)
   VALUES (app_tenant_id(), $1, $2, $3, $4, $5)
   ON CONFLICT (tenant_id, idempotency_key) DO NOTHING
   RETURNING ${COLS}`,
  [idempotencyKey, hash, input.currency, totalCents(input.items), JSON.stringify(input.items)],
);
const order = inserted.rows[0];
if (order) {
  await writeOutbox(c, order); // same transaction as the order
  return { kind: 'created', order };
}
// Otherwise: same key and same body -> return the original order (200);
// same key, different body -> 422.
```

The test for this sends 20 concurrent retries with the same key: one `201`, nineteen `200`, and exactly one outbox event.

### 2. A relay moves committed rows to the queue

A relay in each API process claims unpublished rows, sends them to SQS (in batches of up to 10, the `SendMessageBatch` limit), and marks them published. `FOR UPDATE SKIP LOCKED` lets every API replica run the relay without two replicas claiming the same rows. I admire how much that one clause does: it turns an ordinary table into a safe work queue. From [`api/src/relay.ts`](https://github.com/the-vishal-kumar/multi-tenant-event-driven-ref/blob/main/api/src/relay.ts):

```sql
SELECT id::text, event_id::text, tenant_id::text, event_type, payload, traceparent, tracestate, created_at
  FROM outbox
 WHERE published_at IS NULL AND event_type = ANY($2::text[])
 ORDER BY id
 LIMIT $1
 FOR UPDATE SKIP LOCKED
```

If the relay dies after sending but before marking rows as published, it sends them again. That's deliberate: **at-least-once** delivery, with duplicates handled at the consumer.

### 3. The consumer applies each event at most once

The Go worker records the event id and applies the side effect **in the same transaction**. A second delivery hits the primary key, bumps a counter and changes nothing: the database's own uniqueness rule does the deduplication. From [`worker/internal/store/store.go`](https://github.com/the-vishal-kumar/multi-tenant-event-driven-ref/blob/main/worker/internal/store/store.go):

```sql
INSERT INTO processed_messages (event_id, tenant_id, order_id)
VALUES ($1, app_tenant_id(), $2)
ON CONFLICT (event_id) DO UPDATE
  SET duplicate_deliveries = processed_messages.duplicate_deliveries + 1
RETURNING (xmax = 0)   -- true only for a fresh insert
```

Only if that returns `true` does the worker confirm the order. If the confirmation fails, the transaction rolls back the dedupe row too, so the retry gets a clean attempt.

A tempting false lead: why not an SQS FIFO queue for "exactly once"? FIFO deduplicates on the *send* side, within a 5-minute window (SQS, checked Nov 2026). It doesn't make the consumer's side effect atomic, and it adds throughput limits and head-of-line blocking per message group. The project uses a standard queue plus the dedupe table, and would switch to FIFO only if order mattered (e.g. `created` must be processed before `cancelled`).

### 4. Failures: retry with backoff, then dead-letter with a reason

Retryable failures back off by delaying the message's visibility (the [delayed retries case](/p/delayed-retries) compares ways to do this): base × 2^(attempt-1), capped, with jitter. Production defaults in the [retry design note](https://github.com/the-vishal-kumar/multi-tenant-event-driven-ref/blob/main/docs/adr/0003-retry-and-dlq-policy.md) are a 2 s base, a 5 min cap and 5 attempts. Malformed messages go straight to the dead-letter queue. Everything that ends up there carries a `failure_reason`. A `worker redrive` command replays dead letters after the cause is fixed, and only the messages that were in the dead-letter queue when it started, so a still-broken message can't loop forever. Alarms fire on the main queue's oldest-message age and on any dead-letter depth; publish failures in the relay are logged on every pass.

## The clues under load

Measured with k6 against the project's docker compose stack on one laptop (Intel i7-8550U, 4 cores, ~11 GB RAM; 60 s per rate; 70% new orders, 10% idempotent retries, 20% reads). LocalStack stands in for SQS, and k6 shares the CPU with everything it tests, so these numbers show the *shape* of the system, not AWS capacity. Full method in [`loadtest/results/`](https://github.com/the-vishal-kumar/multi-tenant-event-driven-ref/blob/main/loadtest/results/README.md).

| Target req/s | Achieved | Create p50 / p95 / p99 | HTTP errors | Order created → confirmed, p50 / p95 |
|---:|---:|---|---:|---|
| 100 | 100 | 3.4 / 4.7 / 7.7 ms | 0% | 148 / 219 ms |
| 300 | 300 | 4.3 / 14.5 / 88.2 ms | 0% | 233 / 338 ms |
| 450 | 450 | 9.0 / 151 / 454 ms | 0% | 10.3 / 14.9 s (backlog) |
| 600 | 543 (saturated) | 2.1 / 2.2 / 2.5 s | 0% | 7.1 / 15.4 s; 5,195 still queued |

```mermaid
xychart-beta
  title "Create latency p95 before saturation, ms"
  x-axis ["100 req/s", "300 req/s", "450 req/s"]
  y-axis "ms"
  bar [4.7 , 14.5 , 151]
```

Read the 450 req/s row. The API still answered every request, and most quickly, while confirmations fell up to about 15 seconds behind and caught up after the burst. That's the queue doing its job, and it's a lovely thing to watch: a spike becomes a delay in the background work instead of errors for users. Part of that backlog waits in the outbox table, not in SQS, so the queue's own age alarm can't see all of it: alarm on the age of the oldest unpublished outbox row as well (the project lists this as a gap). At 600 req/s the single Node.js API process itself saturated (about 540 req/s), so the next step would be more API replicas, not a faster worker.

Every check passed at every rate: each replayed request returned the original order, and every order created at 100-450 req/s was confirmed.

Re-run the investigation yourself:

```bash
git clone https://github.com/the-vishal-kumar/multi-tenant-event-driven-ref
cd multi-tenant-event-driven-ref
scripts/demo.sh        # starts everything and walks through retries, duplicates and a poison message
loadtest/run.sh 300    # k6 at 300 requests/s for 60 s
```

## The price of the solution

- **Duplicates are your problem now.** At-least-once delivery means every consumer needs a dedupe key and a transaction around "record it + do it". Skip that and you'll send two emails or ship twice.
- **"Done" becomes "accepted".** The API answers before the work is finished, so the UI needs a status (`pending` → `confirmed`) and, ideally, a way to see failures.
- **You need visibility.** Outbox age, queue age, dead-letter depth, logged publish failures, and a trace from the request to the consumer (the project carries the W3C `traceparent` through the outbox and SQS). Without them, "the queue is slow" is invisible until customers complain.
- **Ordering isn't free.** Standard queues don't preserve order. If it matters, use FIFO with a message group per entity, and accept lower throughput.
- **One more moving part.** The relay is a single small file (about 150 lines with tracing) and is adequate below thousands of events per second. Beyond that, change data capture (e.g. Debezium) removes the polling, but it's another stateful system to run.

> **Remember this**
> - Can I answer the user before this finishes? Then queue it.
> - Never send to the queue from the handler: write an outbox row in the same transaction.
> - Delivery is at least once, so every consumer dedupes.

## What I'd do on Monday

For a SaaS backend: synchronous for anything the user needs to see the result of right now; **outbox + standard queue + idempotent consumer** for everything else that must happen; and fire-and-forget only for data you could lose without anyone noticing. I'd revisit it when event volume reaches thousands per second (change data capture instead of polling) or when per-entity ordering becomes a requirement (FIFO).

The whole solution needs very little cleverness, which is exactly what makes it beautiful. A transaction, a unique key and a retry loop, each doing one job, add up to a system that shrugs off crashes, retries and spikes.

*Checked against: PostgreSQL 17 (the project's image), Amazon SQS documentation, Nov 2026.*
