FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

One Postgres table fixes the dual-write bug your demo hides

Write the event in the same transaction as the order and let a relay send it; if the receiver deduplicates, retries never create duplicates.

ShareLinkedInFacebookX

In brief

  • No single transaction can span your database and the client's system, so the event has to be written to your database first.
  • A relay can send the same event more than once: "never lost" in practice means at-least-once.
  • "No duplicates" is only possible when the receiver deduplicates by event ID, for example through an Idempotency-Key.
Diagram of the transactional outbox architecture. On the left is your database, where the orders table and the outbox table are written in the same transaction. In the middle, a relay reads the outbox using SKIP LOCKED. Two orange arrows run from the relay into the receiver's processed_events table, annotated "×2" and "may send twice". processed_events dedups by event ID before the business change is applied.
Write the order and its outbox event in the same transaction and the event cannot be lost. But the relay may deliver an event more than once, so the receiver must record processed event IDs in a processed_events table, in the same transaction as the business change.

A common piece of code at a client site saves an order to Postgres, commits, then calls a webhook on the client’s ERP. If the process dies between those two lines, the order exists and the ERP never hears about it. Reverse the order and the risk flips: the ERP receives an order that your database has rolled back.

This is the dual-write problem. Debezium’s blog puts it bluntly: there is no single transaction that can span both a service’s database and Apache Kafka. The same holds for a client’s system, and it is harder still because you do not control it.

For an FDE, this is the classic flaw in an integration that “works in the demo”. This guide builds a transactional outbox from scratch with Postgres and Python, ready to take straight to a client.

What you will build, and what you need first

As microservices.io describes it, the outbox answers one question: how to update a database and send a message atomically. The service first stores the message in its database, in the same transaction as the business data, and a relay forwards it afterwards.

You need Postgres running locally, Python 3 and a Postgres driver. The code below follows psycopg 3 conventions and uses an HTTP client such as httpx. It is a stripped-down version for learning: it has no logging, no retry backoff and no configuration, which you should add before production.

Step 1: the outbox table lives in your own database

The core idea, as Debezium describes it, is to put an “outbox” table inside the service’s own database. No intermediate broker, no separate queue.

CREATE TABLE orders (
  id          uuid PRIMARY KEY,
  customer_id text NOT NULL,
  status      text NOT NULL
);

CREATE TABLE outbox (
  id           uuid PRIMARY KEY,
  aggregate_id uuid NOT NULL,
  event_type   text NOT NULL,
  payload      jsonb NOT NULL,
  created_at   timestamptz NOT NULL DEFAULT now(),
  sent_at      timestamptz
);

CREATE INDEX outbox_unsent ON outbox (created_at)
  WHERE sent_at IS NULL;

Check: \d outbox in psql should show outbox_unsent, a partial index covering only unsent rows. The id column is the event ID, which the receiver will later use to deduplicate.

Step 2: write the order and the event in one transaction

Everything else in the pattern rests on this step. Both INSERT statements must sit inside the same transaction block.

import uuid, json

def create_order(conn, customer_id):
    order_id = uuid.uuid4()
    event_id = uuid.uuid4()
    with conn.transaction():
        conn.execute(
            "INSERT INTO orders (id, customer_id, status) VALUES (%s, %s, 'created')",
            (order_id, customer_id),
        )
        conn.execute(
            "INSERT INTO outbox (id, aggregate_id, event_type, payload) "
            "VALUES (%s, %s, 'order_created', %s)",
            (event_id, order_id, json.dumps({"order_id": str(order_id), "customer_id": customer_id})),
        )
    return order_id

Test it by deliberately raising an exception between the two INSERTs. The correct result is that both orders and outbox are empty. An order without an event, or the reverse, means you are running two transactions where there should be one.

Note that this function makes no network call. It touches only your database, so it is fast and never hangs because the client’s API is slow.

Step 3: a polling relay with SKIP LOCKED

Microservices.io lists two ways to build the relay: tailing the transaction log (CDC) or a polling publisher. With plain Python and Postgres, polling is a sensible starting point because it needs no extra infrastructure.

To run several workers, you need SKIP LOCKED. The Postgres documentation explains that with this option any rows that cannot be locked immediately are skipped, and that it can be used to avoid lock contention when multiple consumers read from a queue-like table.

def relay_once(conn, http, url, batch=50):
    with conn.transaction():
        rows = conn.execute(
            "SELECT id, event_type, payload FROM outbox "
            "WHERE sent_at IS NULL ORDER BY created_at "
            "LIMIT %s FOR UPDATE SKIP LOCKED",
            (batch,),
        ).fetchall()
        for event_id, event_type, payload in rows:
            resp = http.post(
                url,
                json={"id": str(event_id), "type": event_type, "data": payload},
                headers={"Idempotency-Key": str(event_id)},
                timeout=10,
            )
            resp.raise_for_status()
            conn.execute("UPDATE outbox SET sent_at = now() WHERE id = %s", (event_id,))

Run this function in a loop with a short sleep. Check: open two terminals running two workers, create 200 orders, then count on the receiving side. Each worker should pick up a different share, and neither should sit waiting on the other.

This is a deliberate simplification: the whole batch runs in one long transaction, holding row locks throughout the HTTP calls. The Postgres documentation also warns that SKIP LOCKED gives an inconsistent view of the data, so use it only for queue-like tables such as the outbox, never for ordinary queries.

Why “never lost” still means “possibly duplicated”

Walk through a concrete case with the version above. A batch holds 50 events. The first 30 POST successfully; the 31st returns a 500. raise_for_status throws, the transaction rolls back, and the 30 earlier UPDATEs go with it.

On the next poll, all 30 events the client already has are sent again. A process killed between POST and UPDATE produces the same outcome. Microservices.io spells out the consequence: the relay might publish a message more than once, so consumers must be idempotent, for example by recording the IDs of messages they have processed.

That is why the Idempotency-Key header carries the event ID itself. You cannot prevent the duplicate send, but you can make it harmless.

A better version: one transaction per event

Duplicates are unavoidable, but resending 30 events because of one failure is wasteful. The simplest fix is to commit per event: each transaction locks exactly one row, sends, marks it, then commits.

def relay_one(conn, http, url):
    with conn.transaction():
        row = conn.execute(
            "SELECT id, event_type, payload FROM outbox "
            "WHERE sent_at IS NULL ORDER BY created_at "
            "LIMIT 1 FOR UPDATE SKIP LOCKED"
        ).fetchone()
        if row is None:
            return False
        event_id, event_type, payload = row
        resp = http.post(
            url,
            json={"id": str(event_id), "type": event_type, "data": payload},
            headers={"Idempotency-Key": str(event_id)},
            timeout=10,
        )
        resp.raise_for_status()
        conn.execute("UPDATE outbox SET sent_at = now() WHERE id = %s", (event_id,))
    return True

Rerun the earlier scenario: the first 30 events have committed sent_at, and only the 31st goes back to the queue. A kill between POST and UPDATE now duplicates exactly one event. Note that with a plain ORDER BY created_at, a failed event is retried immediately, so you need to add backoff.

This version still holds a lock on one row while waiting on HTTP. If the client’s API is slow, the next step is to “claim first”: a short transaction marks the row as taken along with a timestamp and commits, the send happens outside any transaction, and only then is sent_at updated. That requires an extra column and a rule for reclaiming rows held too long, so do it only when you genuinely need it.

Step 4: the receiver deduplicates by event ID

In Debezium’s example, the first thing the handler does is check whether an event with that UUID has already been processed. If you are writing the receiving endpoint yourself, or the client lets you put a buffer layer in front of their system, do this:

CREATE TABLE processed_events (
  event_id     uuid PRIMARY KEY,
  processed_at timestamptz NOT NULL DEFAULT now()
);
def handle_event(conn, event):
    with conn.transaction():
        cur = conn.execute(
            "INSERT INTO processed_events (event_id) VALUES (%s) ON CONFLICT DO NOTHING",
            (event["id"],),
        )
        if cur.rowcount == 0:
            return  # already processed, skip
        apply_business_change(conn, event)

The crucial detail is that the dedup INSERT and the business change share one transaction. Split them and you have rebuilt a miniature dual-write problem.

Check against the scenario above: kill the relay right after the POST. Once the relay restarts, processed_events still holds a single row for that event, and the business change has been applied only once.

When the client already has an idempotent API, follow Stripe

Often you cannot touch the client’s code. In that case, ask whether their API supports idempotency keys. Stripe is a good reference: the client generates a key so the server can recognize retries, Stripe suggests using V4 UUIDs, and keys can be up to 255 characters long.

Stripe stores the first response for each key and returns that same response on every retry, including 500 errors. Keys are pruned after 24 hours, and if an old key comes back with different parameters, Stripe returns an error to prevent accidental misuse.

Those two details give you two questions to put to the client. How long do they keep keys? If your relay can be down for longer than that window, a resent event will be treated as new. And never generate a fresh key for each retry: the key belongs to the event, so every attempt to send it must reuse it.

Common mistakes

The most common is calling the API directly inside create_order “to save time” and treating the outbox as a fallback. That is dual-write again. The second is using an auto-incrementing request ID as the idempotency key, so every retry produces a new key.

The third is letting the outbox table grow forever. The partial index keeps polling queries fast, but you still need a periodic job that removes sent rows, for example:

DELETE FROM outbox WHERE sent_at < now() - interval '7 days';

The seven days here is only an example. The rule is that retention must exceed the receiver’s key-retention window, so that when you investigate a duplicate send you still have the data to check against.

At a client, the outbox starts with a complaint

It is usually some version of “now and then an order doesn’t make it into the accounting system”. The first move is to find every place where code writes to the database and then immediately calls out, and to ask the client how their endpoint handles repeated requests.

When reading job descriptions for FDE or integration engineer roles, watch for phrases such as “at-least-once”, “idempotency”, “webhook” and “CDC”. On a CV, a line like “replaced dual-write with a transactional outbox, with kill-midway tests proving no lost events and no duplicate processing” is far more persuasive than a generic “event-driven”.

A small repo with exactly these four steps, both relay versions and a failure-simulation script is worth bringing to an interview. The interviewer will ask what happens when the relay dies halfway through, and you will have the answer ready in code.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
4 sources
Read next on the roadmap · Stage 2: Broad engineeringStrict schemas still let refusals and truncated JSON throughA Claude refusal comes back with status 200 and a token bill, so your code has to read the stop signal before it parses.