Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

Order confirmation emails are sent with JavaMailSender inside a @Transactional method that saves the order. Customers sometimes get emails for orders that were rolled back, and SMTP slowness makes checkout slow. Redesign it.

Sending the email inside the @Transactional method ties checkout latency to SMTP and sends the email before we know the commit succeeded, so a later rollback leaves a confirmation for an order that does not exist. The quick fix is to publish an event and send from a @TransactionalEventListener(phase = AFTER_COMMIT), ideally asynchronously. The reliable design is the outbox pattern: write an email request row in the same transaction as the order, and let a worker send it with retries, using a message id so retries never send duplicates, while tracking bounces and keeping templates versioned.

Why this question is asked

This is a classic case of two systems that cannot share a transaction: the database and the mail server. The code looks natural, save the order, send the email, but the order of events hides two bugs, one about correctness and one about latency. Interviewers ask it because the fixes form a ladder, from a small change that solves most of it to a pattern that solves all of it, and a strong answer explains what each step buys. In this answer, we will see why the current code fails, then move the send after the commit, make it asynchronous, replace it with an outbox for reliability, and finally make delivery idempotent and observable.

1Why the Current Design Fails

A database transaction makes a group of changes all-or-nothing, and nothing is final until the commit at the end of the method. Sending an email is not part of that transaction: once the SMTP server accepts the message, it is gone, and no rollback can call it back.

Java
@Transactional
public Order checkout(Cart cart) {
Order order = orders.save(Order.from(cart)); // INSERT, not yet committed
mailer.sendConfirmation(order); // SMTP: 800 ms on a slow day, email already sent
inventory.reserve(order); // throws OutOfStockException
return order; // never reached: the transaction rolls back
}
// result: no order in the database, but the customer has a confirmation email
Step throughToday: the email leaves before the commit
CheckoutDatabaseSMTP
BEGIN; INSERT order
send confirmation (slow, cannot be undone)
accepted
reserve stock fails
ROLLBACK: order gone, email already sent

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

So there are two problems. First, correctness: anything that fails after the send, a later statement, a constraint checked at flush time, or the commit itself, rolls back the order but not the email. Second, latency: the transaction stays open, holding a database connection and row locks, for as long as SMTP takes. On a slow day that adds seconds to every checkout and can exhaust the connection pool.

2Send Only After the Commit

Spring can run code at a specific point in a transaction's life. We publish an event inside the transaction, and a @TransactionalEventListener with phase AFTER_COMMIT receives it only if the commit succeeds. If the transaction rolls back, the event is simply dropped.

Java
record OrderPlaced(long orderId, String email, Locale locale) {}
@Transactional
public Order checkout(Cart cart) {
Order order = orders.save(Order.from(cart));
inventory.reserve(order);
events.publishEvent(new OrderPlaced(order.id(), cart.email(), cart.locale())); // held until commit
return order;
}
@Component
class ConfirmationSender {
@Async("mailExecutor")
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void on(OrderPlaced e) {
mailer.sendConfirmation(e); // runs after commit, on a mail thread
}
}

Notice @Async. Without it, the listener runs on the checkout thread right after the commit, so the customer still waits for SMTP even though the database connection is free. With it, checkout returns as soon as the commit is done.

But there is a catch. The email now lives only in memory between the commit and the send. If the service crashes or is redeployed in that window, or SMTP is down and the in-memory retries give up, the order exists and the email is lost forever. For confirmations that customers rely on, that is not good enough.

3The Outbox Pattern for Reliability

The outbox pattern closes that gap by turning the email into data. In the same transaction that saves the order, we insert a row into an email_outbox table. Because both rows commit together, there are only two outcomes: order and email request both exist, or neither does. A separate worker then reads pending rows, sends them, and marks them sent.

SQL
CREATE TABLE email_outbox (
id uuid PRIMARY KEY, -- also used as the message id
template text NOT NULL, -- 'order-confirmation'
template_v int NOT NULL, -- 3
recipient text NOT NULL,
payload jsonb NOT NULL, -- order id, locale, totals
status text NOT NULL DEFAULT 'PENDING',
attempts int NOT NULL DEFAULT 0,
next_try_at timestamptz NOT NULL DEFAULT now()
);
-- worker, every few seconds:
SELECT * FROM email_outbox
WHERE status = 'PENDING' AND next_try_at <= now()
ORDER BY next_try_at LIMIT 50
FOR UPDATE SKIP LOCKED; -- several workers never take the same row
Step throughCheckout and delivery with an outbox
  1. Checkout transactionINSERT order + INSERT outbox row, one commit
  2. Worker picks PENDING rowsFOR UPDATE SKIP LOCKED
  3. Send with message idprovider accepts or fails
  4. Accepted?
    YesMark SENTNoattempts + 1, back off, retry
  5. Attempts exhausted?after about 5 tries
    YesMark FAILED and alertNoWait for next_try_at

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

The worker sends each email, sets status to SENT on success, and on failure increases attempts and pushes next_try_at forward with backoff, for example 1, 5 and 30 minutes, until a limit after which the row is marked FAILED for someone to look at. Checkout now does one extra INSERT and never touches SMTP. Instead of polling, the outbox can also be read by change data capture into a message broker, which suits larger systems.

4Idempotent Sending

Retries bring their own risk. The worker might send an email and crash before marking the row SENT. On restart it sends again, and the customer gets two confirmations. We cannot make this impossible, because the send and the status update are again two systems, but we can make it harmless.

The outbox row's id serves as the message id. We send it as the Message-ID header, and with an email provider API that supports it, as an idempotency key, so the provider ignores a second request with the same key. Where the provider does not deduplicate, we keep a record of sent ids and check it before sending, which narrows the duplicate window to a crash in the middle of one send.

5Bounces and Versioned Templates

Sending is not the same as delivering. Mail can bounce because the address does not exist (a hard bounce) or the mailbox is full (a soft bounce), and recipients can mark it as spam. Most email providers report these through webhooks. We record them against the outbox row and the customer, stop sending to hard-bounced addresses, and show support staff that the confirmation did not arrive.

Templates should be versioned, because an outbox row may wait minutes or hours before it is sent, and a deployment in between could change the template. Storing template and version in the row, and keeping old versions until no pending row uses them, means every email is rendered with the template it was created for.

6Follow-up questions

Why not just use @TransactionalEventListener without the outbox?

It is a fine first step and fixes both the rollback bug and the latency, but the event lives only in memory. A crash, a redeploy or an SMTP outage longer than the in-memory retries loses the email. The outbox stores the intent durably in the same commit as the order.

What if the outbox worker falls behind?

Emails arrive late but are not lost, which is the right failure mode. We monitor the age of the oldest PENDING row and alert if it passes, say, 5 minutes, and scale workers or investigate the provider.

Can the listener run BEFORE_COMMIT instead?

BEFORE_COMMIT runs inside the transaction, so a failure there still rolls back the order, and the commit itself can still fail afterwards. It is useful for last-moment database work, not for side effects like email that must only happen once the data is safe.

7Conclusion

In this answer, we saw that sending inside the transaction couples checkout to SMTP and sends emails for rolled-back orders. Moving the send to an asynchronous AFTER_COMMIT listener fixes both, the outbox pattern makes the email as durable as the order, a message id keeps retries from sending duplicates, and bounce tracking with versioned templates makes delivery observable and stable.

What to say in the interviewAbout 90 seconds aloud

Open with

The current design has two problems. The email is sent inside the transaction, so if anything fails afterwards, a later statement or the commit itself, the order rolls back but the email is already gone.

Then, if they want more

And the transaction stays open while we wait for SMTP, holding a connection and locks, so a slow mail server makes checkout slow. The first fix is to publish an OrderPlaced event inside the transaction and send from a @TransactionalEventListener with phase AFTER_COMMIT, marked @Async so the customer doesn't wait for SMTP at all. That only sends for committed orders.

But the event lives in memory, so a crash or a long SMTP outage loses it. For confirmations I'd use the outbox pattern: in the same transaction as the order, insert a row into an email_outbox table with the template name and version, recipient and payload. They commit together, so either both exist or neither does.

A worker selects pending rows with FOR UPDATE SKIP LOCKED, sends them, marks them sent, and on failure backs off and retries until a limit, then alerts. Because a crash between sending and marking sent would cause a resend, I'd use the outbox id as the message id and idempotency key with the provider.

Finally I'd record bounces from provider webhooks, stop sending to hard-bounced addresses, and keep templates versioned so delayed emails render correctly.

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 "Order confirmation emails are sent with JavaMailSender inside a @Transactional method...": https://scrivio-interview-library.netlify.app/spring-boot/spring-utilities/cf7a111838/