Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A payments service occasionally sends duplicate confirmation emails. The code checks

Java
if (!order.isConfirmed()) {
sendEmail();
order.setConfirmed(true);
save(order);
}

and two instances process the same event. What would you do?

This is a check-then-act race: both instances read the order, both see confirmed = false, and both send the email before either one saves. A lock inside one JVM cannot stop another instance, so the fix has to live in the shared database: claim the order with an atomic conditional update such as UPDATE orders SET confirmed = true WHERE id = ? AND confirmed = false, and send only if that update changed one row, or use optimistic locking with a version column. Because retries can still repeat a send, the email itself should also carry an idempotency key.

Why this question is asked

Duplicate emails sound minor, but the same bug pattern sends duplicate payments, double shipments and repeated refunds. It appears as soon as we run more than one instance or our message broker delivers an event twice, which every broker is allowed to do. Interviewers ask this to see whether we recognise the race, whether we know that synchronized stops at the edge of one process, and whether we can make a side effect such as an email safe to retry. In this answer, we will name the race and walk through the interleaving, see why in-memory locks fail, then build the fix in three layers: an atomic claim in the database, the optimistic locking alternative, and idempotent sending.

1Naming the Race: Check-Then-Act

A check-then-act sequence reads some state, makes a decision from it, and then acts on that decision. It is correct only if nothing can change the state between the check and the act. Here the check is order.isConfirmed(), the act is sendEmail() followed by setConfirmed(true) and save(order), and the gap between them includes a network call to the email service, which can take hundreds of milliseconds.

Two instances receive the same event, for example because the broker redelivered it after a timeout, or because a retry upstream published it twice. Both load the order row while it still says confirmed = false. Both decide to send. Both send. Then both save confirmed = true, and the second save happily overwrites the first with the same value. Nothing fails, nothing is logged, and the customer gets two emails.

Step throughBoth instances pass the check before either saves
Instance 1DatabaseInstance 2Email service
load order 42
confirmed = false
load order 42
confirmed = false
send confirmation
send confirmation (duplicate)
save confirmed = true
save confirmed = true (no error)

8 messages in order. Play them, or step through them one at a time.

2Why In-JVM Locks Do Not Help

The first idea is often to put synchronized on the method, or to use a ReentrantLock keyed by order id. That does stop two threads in the same process from overlapping. But each instance is a separate JVM with its own memory, so instance 1's lock is an object that instance 2 cannot see. The two instances still race exactly as before.

A distributed lock in Redis or ZooKeeper can coordinate instances, but it adds a new system, lock expiry and the classic problem of a process that pauses past its lease and then carries on as if it still held the lock. We already have a system that every instance shares and that can make an atomic decision: the database that holds the order. So we let the database decide who wins.

3Fix 1: Claim the Order With an Atomic Conditional Update

Instead of reading confirmed and then writing it, we do both in a single statement. The database runs an UPDATE with a WHERE clause atomically for each row, taking a row lock while it does so, so only one transaction can flip the flag from false to true. The statement returns the number of rows it changed, and that number tells us whether we won.

Java
public interface OrderRepository extends JpaRepository<Order, Long> {
@Modifying
@Query("update Order o set o.confirmed = true where o.id = :id and o.confirmed = false")
int claimConfirmation(@Param("id") long id);
}
@Transactional
public void onOrderPaid(long orderId) {
int changed = orders.claimConfirmation(orderId);
// Instance 1: changed = 1, it flipped the flag
// Instance 2: changed = 0, the row no longer matches confirmed = false
if (changed == 1) {
outbox.save(new EmailTask(orderId, "order-confirmed:" + orderId));
}
}

Notice the order of operations. We claim first and send afterwards, and we do not call the email service inside the database transaction at all. Instead we write a row to an outbox table in the same transaction as the claim. A separate worker reads the outbox and sends the email. This is the transactional outbox pattern, and the reason for it is that a database commit and an email send cannot be made atomic together: if we sent first and the commit failed, we would have sent an email for a change that never happened; if we committed and then crashed before sending, we would lose the email. The outbox row makes the intent durable in the same commit as the claim.

If the second instance's update arrives while the first transaction is still open, it simply waits for the row lock, then re-checks the condition after the first commits, finds confirmed = true, and changes 0 rows.

4Fix 2: Optimistic Locking With a Version Column

When the decision is more complex than flipping one flag, for example when several fields change together, we can keep the read-modify-write style and let JPA detect the clash. We add a version column. Every update includes the version we read in its WHERE clause and increments it, so an update based on a stale read changes no rows, and Hibernate turns that into an exception.

Java
@Entity
class Order {
@Id Long id;
boolean confirmed;
@Version long version; // 7 when both instances load the row
}
// Hibernate issues: update orders set confirmed=true, version=8 where id=42 and version=7
// Instance 1: 1 row updated, commit succeeds
// Instance 2: 0 rows updated -> ObjectOptimisticLockingFailureException, transaction rolls back

For this to stop the duplicate, the email must again go through the outbox in the same transaction, so that the loser's rollback also discards its email task. The loser can then reload the order, see that it is confirmed, and do nothing. The conditional update is simpler for a single flag; optimistic locking scales better to richer changes. A unique constraint, for example on a sent_notifications table keyed by order id and email type, is a third database-level guard that works even when the code path changes later.

5Fix 3: Make the Send Itself Idempotent

Even with a perfect claim, the outbox worker can send an email, crash before it marks the task done, and send it again after restart. Networks also time out after the provider has accepted a message, so the worker retries a send that actually worked. At-least-once delivery is the honest guarantee here, which means the final step must tolerate repeats.

So each email task carries a stable idempotency key, such as order-confirmed:42. Many email providers accept such a key and drop a second request with the same key within a time window; check your provider's API for the exact header. If the provider does not, the worker records the key in a table with a unique constraint before sending, so a second attempt finds the key and skips. Now duplicates are stopped at every layer: the database decides who confirms, the outbox makes the intent durable, and the key makes retries harmless.

Step throughProcessing a payment event safely
  1. Event arrives (possibly twice)from any instance
  2. Conditional update changed 1 row?
    YesWrite outbox task in the same transactionNoAnother instance already won; stop
  3. Commitclaim and task saved together
  4. Outbox worker sends with idempotency keyorder-confirmed:42
  5. Send confirmed by provider?
    YesMark task doneNoRetry later with the same key

5 steps in order. Play them, or step through them one at a time.

6Follow-up questions

Why not just make the event consumer process each message exactly once?

Brokers such as Kafka can give exactly-once semantics within Kafka itself, from a topic to a topic, but the effect we care about here is an email sent to an outside system and a row in our database. The broker cannot make those exactly-once for us. Consumers must be idempotent anyway, because rebalances, timeouts and producer retries all cause redelivery, so the database claim is the reliable place to deduplicate.

What isolation level does the conditional update need?

The default READ COMMITTED is enough in PostgreSQL and MySQL. The UPDATE takes a row lock, and if another transaction changed the row first, the database waits for it and then re-evaluates the WHERE condition against the committed row, so the second update matches nothing. We do not need SERIALIZABLE for a single-row atomic update.

Would a distributed lock in Redis be wrong here?

It can work, but it is weaker and more complex than using the database we already write to. A lock lease can expire while a process is paused by garbage collection or a slow network, and then two holders act at once. The conditional update makes the decision in the same place the state lives, so there is no gap between holding the lock and changing the data.

7Conclusion

In this answer, we saw that the duplicate emails come from a check-then-act race across two instances: both read confirmed = false before either saves. In-memory locks only coordinate threads in one JVM, so we moved the decision into the database with a conditional UPDATE that reports how many rows changed, saw optimistic locking with a version column as the alternative for richer updates, used a transactional outbox so the claim and the email intent commit together, and made the send idempotent with a stable key so that retries cannot duplicate it.

What to say in the interviewAbout 90 seconds aloud

Open with

This is a check-then-act race. Two instances get the same event, both load the order while confirmed is still false, both send the email, and then both save confirmed true, so nothing fails and the customer gets two emails.

Then, if they want more

A synchronized block or an in-memory lock would not help because each instance is a separate JVM. I would let the database make the decision atomically: an UPDATE orders SET confirmed = true WHERE id = ? AND confirmed = false, and only the caller that gets one row changed goes on.

In Spring Data that is a @Modifying query returning an int. If the update is more complex, optimistic locking with a @Version column gives the same effect, because the stale writer updates zero rows and gets an optimistic locking exception.

I would not send the email inside that transaction; I would write an outbox row in the same commit and have a worker send it, so the claim and the intent to send are atomic.

Finally, sending is still at least once, because the worker can crash after a successful send, so each email carries an idempotency key like order-confirmed plus the order id, either supported by the provider or checked against a unique constraint before sending. I would also add a metric for skipped duplicates so we can see how often redelivery happens.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A payments service occasionally sends duplicate confirmation emails. The code checks": https://scrivio-interview-library.netlify.app/java/concurrency-problems/fc47728c78/