The N+1 query that hid in a mapper

A profiling story. The endpoint was slow, the SQL looked fine, and the cause was somewhere I was sure it could not be.

Backend work is mostly about effects, not messages. A request can arrive twice; the thing it triggers must not happen twice. The sooner you design for that, the calmer your on-call rotation gets.

The trick is a stable key the system can dedupe on, plus a durable place to remember which keys it has already handled — ideally the same transaction that performs the work.

Below is the shape I reach for. If the insert conflicts, the work was already done — we ack and move on. No distributed lock, no second system to keep in sync. Boring, durable, predictable.

OrderConsumer.java java
1 void handle(Message m) {
2 // the message may arrive twice; the effect must not
3 String key = m.dedupeKey();
4 tx.run(() -> {
5 if (seen.contains(key)) return; // already done — ack
6 seen.mark(key);
7 work(m);
8 });
9 }

That’s the whole idea. The hard part was never delivery — it was deciding what “the same job” means, and writing it down somewhere durable.