Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

In a Spring Boot payment service, a method charges a card through an external provider and then saves a Payment entity. Sometimes the provider charge succeeds but the save fails, and the customer is charged with no record. How would you restructure the code?

I would split the work into three steps. First save a Payment row with status PENDING and a generated id in its own committed transaction. Then call the provider outside any transaction, passing the payment id as the provider's idempotency key. Finally update the row to SUCCEEDED or FAILED in a second transaction, and run a scheduled reconciliation job that asks the provider about payments stuck in PENDING, so a charge is never left without a record.

Why this question is asked

Charging a card and saving a record looks like one operation, but it spans two systems that cannot share a transaction: our database and the payment provider. When the order of operations is wrong, a crash or a failed save at the wrong moment leaves a customer charged with no record, which means angry customers, manual refunds and accounting differences. Interviewers ask this question to see whether we understand that a remote call cannot be rolled back and how to design around it. In this answer, we will reproduce the problem, see why a transaction cannot fix it, restructure the code into three steps, add reconciliation for the cases that still go wrong, and explain why the transaction must never span the remote call.

1Reproducing the Problem

Here is the kind of code that causes it. One method, one transaction, the remote call in the middle.

Java
@Transactional
public Payment pay(PayRequest req) {
ChargeResult r = provider.charge(req.cardToken(), req.amount()); // customer is charged now
Payment p = new Payment(req.orderId(), req.amount(), r.chargeId());
return paymentRepository.save(p); // fails: constraint violation, DB down, or the pod is killed
} // rollback: no Payment row, but the charge stays

The provider charge is final the moment it succeeds. If anything after it fails, the save itself, the commit, or the process being killed during a deployment, the transaction rolls back and our database forgets the payment ever happened. The customer sees a charge on the card; we have nothing to show for it, and a retry from the client might charge them again.

2Why the Transaction Cannot Help

A database transaction makes changes inside one database atomic: all of them commit or none do. The provider is not part of that transaction. Spring's @Transactional rolls back our inserts, but it cannot un-charge a card. Moving the save before the charge inside the same transaction does not help either: the row is not committed until the method ends, so if the process dies after the charge, the uncommitted row is gone too.

There is a second problem. Holding a database transaction open across a remote call that may take 2 to 30 seconds keeps a connection from the pool busy and may hold row locks the whole time. Under load, slow provider responses exhaust the connection pool and the entire service stops. So the remote call must sit between two short transactions, not inside one.

3The Fix: Record First, Call, Then Record the Outcome

We restructure into three steps. Each database step is its own short transaction, and the remote call happens with no transaction open.

Java
public Payment pay(PayRequest req) {
Payment p = tx.execute(s -> paymentRepository.save(
Payment.pending(UUID.randomUUID(), req.orderId(), req.amount()))); // committed: status PENDING
ChargeResult r;
try {
r = provider.charge(req.cardToken(), req.amount(),
p.getId().toString()); // idempotency key = our payment id
} catch (ProviderTimeoutException e) {
return p; // stays PENDING; reconciliation decides
}
return tx.execute(s -> {
Payment fresh = paymentRepository.findById(p.getId()).orElseThrow();
if (r.succeeded()) fresh.markSucceeded(r.chargeId()); // status SUCCEEDED
else fresh.markFailed(r.declineCode()); // status FAILED
return fresh;
});
}
Step throughThe restructured payment flow
PaymentServiceDatabaseProvider
tx 1: insert payment PENDING, commit
charge(amount, idempotency key = payment id)
succeeded, chargeId
tx 2: update to SUCCEEDED, commit

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

No transaction is open while the provider is called.

Here tx is a TransactionTemplate, so each block commits on its own and the method itself is not @Transactional. Notice what each step buys us. Because the PENDING row is committed before the call, there is always a record of the attempt, whatever happens next. Because the payment id is sent as the idempotency key, if we call the provider again for the same payment, after a timeout or a retry, the provider recognises the key and returns the original result instead of charging twice. Most providers support this, usually as an Idempotency-Key header. And because no transaction is open during the call, a slow provider ties up no database connection.

4Reconciliation for Stuck Payments

The restructuring does not remove failure; it makes every failure visible. If the process dies after the charge but before step three, or the provider call times out, the row stays PENDING. So a scheduled job looks for payments that have been PENDING for longer than a few minutes and asks the provider what really happened, by the same idempotency key or the provider's lookup API.

Java
@Scheduled(fixedDelay = 60_000)
void resolveStuckPayments() {
var cutoff = Instant.now().minus(Duration.ofMinutes(5));
for (Payment p : paymentRepository.findByStatusAndCreatedAtBefore(Status.PENDING, cutoff)) {
ProviderStatus s = provider.lookup(p.getId().toString()); // by idempotency key
tx.executeWithoutResult(t -> {
Payment fresh = paymentRepository.findById(p.getId()).orElseThrow();
switch (s.state()) {
case CHARGED -> fresh.markSucceeded(s.chargeId()); // charge happened: record it
case DECLINED -> fresh.markFailed(s.reason());
case NOT_FOUND -> fresh.markFailed("never reached provider");
}
});
}
}

Now the worst case is that a payment shows PENDING for a few minutes before it is resolved, never a charge without a record. The order flow should treat PENDING as "not yet confirmed" and wait for the final status. In a real system we would also cap how long a payment can stay unresolved and alert on that, and compare against the provider's daily settlement report as a final check.

5The Rule to Remember

Never hold a database transaction open across a remote call. Persist your intent first, call the remote system with an idempotency key derived from that intent, record the outcome in a separate transaction, and have a process that resolves anything left in between. The same pattern applies to sending emails, calling shipping APIs or any external side effect that cannot be rolled back.

6Follow-up questions

Why not put the charge in an @TransactionalEventListener after commit?

That ensures the row is committed before the charge, which is an improvement, but the event lives only in memory. If the process dies after the commit and before the listener runs, the payment stays PENDING with no attempt made, and nothing triggers it again except reconciliation. It also hides the remote call in a listener, which makes the flow harder to follow. Explicit steps plus reconciliation are clearer and handle every crash point.

What should the API return to the client while the payment is PENDING?

Usually 202 Accepted with the payment id and status PENDING, and the client polls or receives a webhook when the status changes. If the provider normally answers in under two seconds, the endpoint can wait for the result and return the final status in most cases, falling back to PENDING only on timeouts. The client must never retry by creating a new payment; it should retry with the same request idempotency key so it gets the same payment.

7Conclusion

In this answer, we saw why charging inside a transaction and then saving can leave a customer charged with no record: the transaction rolls back our row but cannot undo the remote charge. We restructured the code into a committed PENDING row, a provider call outside any transaction with the payment id as idempotency key, and a second transaction recording SUCCEEDED or FAILED. A reconciliation job resolves payments stuck in PENDING, and the general rule is never to hold a transaction open across a remote call.

What to say in the interviewAbout 90 seconds aloud

Open with

The root issue is that the provider charge and our database save are in two systems that cannot share a transaction. If the charge succeeds and the save or commit fails, or the pod is killed in between, Spring rolls back our insert but the card is still charged.

Then, if they want more

Wrapping it all in @Transactional cannot fix that, and it adds another problem: the transaction holds a database connection for the whole remote call, which can exhaust the pool when the provider is slow. So I would restructure it into three steps.

First, in its own short transaction, I save a Payment with a generated id and status PENDING and commit it, so there is always a record of the attempt.

Second, with no transaction open, I call the provider and pass our payment id as the idempotency key, so if we retry the call the provider returns the original result instead of charging again. Third, in a second short transaction, I update the payment to SUCCEEDED with the provider's charge id, or to FAILED.

If the call times out or we crash before step three, the payment simply stays PENDING. A scheduled reconciliation job picks up payments that have been PENDING for more than a few minutes, asks the provider by the idempotency key what actually happened, and sets the final status.

The worst case becomes a short delay in status, never a charge without a record.

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 official documentation for the version you use. 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 "In a Spring Boot payment service, a method charges a card through an external provider...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/42ea582210/