Video in progress

Strong Middle 🧩 Microservices

When delivering events from the outbox table to the broker, how do polling and CDC (Debezium) differ?

Polling is simple: a scheduler reads the unsent rows from the table and ships them, but it adds extra queries to the database and some delay. CDC reads the transaction log, has low delay and preserves order, but it needs infrastructure like Kafka Connect.

📖 Answer

Polling relay:

@Scheduled(fixedDelay = 500)
@Transactional
public void publish() {
    List<OutboxEvent> batch = jdbc.query("""
        SELECT * FROM outbox WHERE sent_at IS NULL
        ORDER BY id LIMIT 100
        FOR UPDATE SKIP LOCKED
        """, mapper);
    for (OutboxEvent e : batch) {
        kafka.send("orders", e.aggregateId(), e.payload()).join();
        jdbc.update("UPDATE outbox SET sent_at = now() WHERE id = ?", e.id());
    }
}

FOR UPDATE SKIP LOCKED is so that several pods don't take the same rows. But there's a subtle point: if parallel pods take the events of one aggregate in different batches, the order can break. In that case you use a single relay (a leader) or split by aggregate.

Also: ordering by an IDENTITY id doesn't guarantee commit order: a transaction with a smaller id may commit later, and the relay can skip it if you use a "last read id" cursor. The sent_at IS NULL approach is free of this problem.

CDC (Debezium): it reads the PostgreSQL WAL (or the MySQL binlog) and sends every row added to the outbox to Kafka. Debezium has a dedicated "event router" transformation for outbox. Advantages: events arrive in commit order, there's no polling load, and the delay is in milliseconds. The cost: running a Kafka Connect cluster and watching the replication slot, which, if it stops, lets WAL fill the disk.

In both cases the guarantee is at-least-once. On a small project I start with polling, and move to CDC when the load or ordering requirements grow.