Video in progress

Strong Middle 🧩 Microservices

The outbox table grows every day and events reach the broker late. What do you check and how do you fix it?

This is usually two problems: sent rows are not being deleted (the table and index bloat, polling slows down) and the relay can't keep up with the write rate. A cleanup job, a partial index, batched sending and a relay lag metric are often enough.

📖 Answer

The first step is to measure: a metric for "how many seconds ago was the oldest unsent event created". If that number keeps growing, the relay is behind.

Common causes:

  1. Sent rows stay forever. On a table with 50 million rows, WHERE sent_at IS NULL ORDER BY id walks a big index every time. The fix is a partial index plus cleanup:
CREATE INDEX outbox_unsent ON outbox (id) WHERE sent_at IS NULL;

-- every hour, in chunks
DELETE FROM outbox
WHERE id IN (SELECT id FROM outbox
             WHERE sent_at < now() - interval '3 days'
             LIMIT 10000);

At very large volumes, partitioning by time and running DROP on the old partition is much cheaper than DELETE.

  1. The relay sends each event separately and synchronously: send(...).get(), so each one costs a broker round trip. Sending 100 events in a row, then waiting for all the futures and doing a single UPDATE ... WHERE id = ANY(?) raises throughput several times over.

  2. A single poison row. The payload can't be serialized or the topic doesn't exist, so the relay fails on that row and blocks the ones after it. Store the number of attempts (attempts), move rows over the limit to a FAILED state and raise an alert.

  3. In PostgreSQL, a long-open transaction keeps autovacuum from cleaning up dead rows, and the table keeps bloating. Look in pg_stat_activity for sessions with an old xact_start.

With Debezium the picture is different: you can delete the row immediately, even in the same transaction, because CDC reads the event from the WAL. What you watch there is the replication slot lag.