Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

Review this code and list the problems:

Java
@Transactional
public void syncAll() {
for (Customer c : customerRepository.findAll()) {
try {
crmClient.push(c);
} catch (Exception e) { }
}
}

The method swallows every exception without logging or metrics, so failures are invisible, and catching Exception also hides programming errors. findAll() loads every customer into memory at once, and @Transactional keeps one transaction and one database connection open for the whole run, including every remote CRM call. There is no retry, no idempotency and no record of progress, so a crash halfway means starting again. The fix is to read customers in batches in short transactions, make the remote calls outside any transaction, catch specific exceptions with logging and metrics, and record each customer's outcome so the job can retry and resume.

Why this question is asked

Short methods like this one are some of the most dangerous code in a service, because they look harmless in review and only show their problems at production scale. With a hundred test customers it works perfectly; with two million real ones it runs out of memory, starves the connection pool, or reports success while silently failing for thousands of customers. Interviewers use it to see how many layers of problems we can spot and whether our fix addresses the design rather than only the symptoms. In this answer, we will read the code, go through each problem with its consequence at real scale, and then rewrite the job step by step.

1Reading the Code

Here is the method, spread out so we can comment on each line.

Java
@Transactional
public void syncAll() {
for (Customer c : customerRepository.findAll()) { // every customer, all at once
try {
crmClient.push(c); // a remote HTTP call per customer
} catch (Exception e) {
// nothing
}
}
}

The intent is clear: send every customer to the CRM, an external customer relationship system. Let us assume the service has 2 million customers and a CRM call takes about 50 milliseconds. Those two numbers are enough to see most of the problems.

2Problem 1: Failures Are Invisible

The empty catch block swallows every exception. If the CRM is down for an hour, every push fails, the method returns normally, and the job reports success. Nobody knows that a million customers were not synced until a sales team complains weeks later. There is no log line, no metric and no alert.

Catching Exception makes it worse, because it also catches programming errors. A NullPointerException from a customer with no email, or an IllegalArgumentException from a mapping bug, is silently ignored too, so a bug that affects every customer looks exactly like success. At a minimum, every failure must be logged with the customer id and counted in a metric, and we should catch only the exceptions we expect from the CRM call, so real bugs surface.

3Problem 2: findAll() Loads Everything Into Memory

findAll() returns a List with every customer as a managed JPA entity. With 2 million customers at a few kilobytes each, including their loaded associations, that is several gigabytes of heap, and Hibernate's persistence context also keeps a snapshot of each entity for dirty checking, which roughly doubles the cost. The job either fails with OutOfMemoryError or causes long garbage collection pauses that slow every other request in the same service.

The fix is to read in batches, for example 500 customers at a time, using keyset paging on the id, which stays fast however deep we go, unlike OFFSET paging, which gets slower on later pages. Each batch is processed and then released before the next one is read.

4Problem 3: A Transaction Held Open Across Remote Calls

@Transactional on syncAll() opens one transaction for the whole loop. A transaction holds a database connection from the pool until it ends. With 2 million calls at 50 milliseconds, the loop runs for about 100,000 seconds, almost 28 hours, and the connection is held the whole time, mostly while waiting for the CRM. In PostgreSQL, a transaction that long also holds back vacuum, so dead rows accumulate in busy tables and the database slowly bloats.

Step throughOne transaction wrapped around two million remote calls
syncAll()DatabaseCRM
begin transaction, take a pooled connection
select * from customer (2 million rows)
push(customer 1), 50 ms
200 OK
push(customer 2) ... push(customer 2,000,000)
some fail: exceptions swallowed
commit, about 28 hours later

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

The connection and the transaction stay open while the code only waits for the CRM.

5Problem 4: No Retry, No Idempotency, No Progress

Remote calls fail sometimes: a timeout, a 503 during a deployment. Here a failed push is simply dropped, with no retry. If the job crashes or the pod is restarted at customer 1.5 million, there is no record of where it got to, so the next run starts from the beginning and resends 1.5 million customers. That is only safe if the CRM treats a repeated push as an update rather than creating duplicates, which is the property called idempotency, and nothing here guarantees it.

So a robust job needs three things: a limited retry with backoff for transient failures, a record of each customer's outcome, and pushes that are safe to repeat, for example by sending a stable idempotency key or using an upsert endpoint keyed on our customer id.

6The Rewrite

Putting the fixes together, the job reads small batches in short read-only queries, makes the remote calls with no transaction open, and records the outcome of every customer.

Java
@Component
class CustomerCrmSync {
void syncAll() { // no @Transactional here
long lastId = 0;
List<CustomerView> batch;
do {
batch = customers.findTop500ByIdGreaterThanOrderByIdAsc(lastId); // short query, connection returned at once
for (CustomerView c : batch) syncOne(c);
if (!batch.isEmpty()) lastId = batch.getLast().id(); // List.getLast(): Java 21+
} while (!batch.isEmpty());
}
private void syncOne(CustomerView c) {
try {
crmClient.upsert(CrmCustomer.from(c), "customer-" + c.id() + "-v" + c.version()); // idempotency key
outcomes.markSynced(c.id(), c.version()); // its own short transaction
metrics.counter("crm.sync", "result", "ok").increment();
} catch (CrmUnavailableException | CrmTimeoutException e) { // expected, retryable failures only
outcomes.markFailed(c.id(), e.getMessage()); // picked up by the next run
metrics.counter("crm.sync", "result", "failed").increment();
log.warn("CRM sync failed for customer {}", c.id(), e);
}
}
}

Notice the key changes. CustomerView is a projection, a small read-only record with just the fields the CRM needs, so we do not load full entities or keep them in a persistence context. Each batch query borrows a connection for milliseconds. The CRM call happens with no transaction open. Only expected CRM failures are caught; a NullPointerException now fails the job loudly, which is what we want for a bug. Every outcome is recorded, so a dashboard can show how many customers failed and the next run can retry only those, or skip customers whose current version is already synced.

For transient errors, a retry with backoff inside crmClient, for example two retries at 200 and 800 milliseconds, handles brief blips; Resilience4j or Spring Retry can do this, and Spring Framework 7 also includes built-in retry support, so check your version. For very large volumes, running batches in parallel with a bounded number of concurrent CRM calls, or sending changes through an outbox and a message queue, scales further.

7Follow-up questions

Why not just make the transaction smaller by putting @Transactional on push?

Because the remote call is the slow part, and a transaction around it still holds a connection while waiting for the CRM. Transactions should cover only database work. Here the reads need no transaction beyond the query itself, and recording each outcome is a short transaction of its own.

Would Spring Data's Stream<Customer> fix the memory problem?

It reduces memory, because rows are fetched as we iterate, but a repository Stream must be consumed inside a transaction with an open connection, so it brings back problem 3 for the whole run. It also still fills the persistence context unless we detach entities. Keyset batches with projections avoid both problems.

How would you know the job is healthy in production?

From the metrics and the outcome table: counts of synced and failed customers per run, the age of the oldest unsynced change, and the run duration. An alert on a high failure rate or on stale data tells us about a CRM outage within minutes instead of weeks.

8Conclusion

In this answer, we reviewed a four-line method that hides several production problems. Its empty catch of Exception makes failures and bugs invisible, findAll() loads every customer into memory, @Transactional holds a connection and a long transaction open across millions of remote calls, and nothing supports retry, idempotency or resuming. We rewrote it to read keyset batches of projections in short queries, call the CRM outside any transaction with an idempotency key, catch only expected failures with logs and metrics, and record each customer's outcome so the job can retry and resume.

What to say in the interviewAbout 90 seconds aloud

Open with

I see four groups of problems. First, the empty catch of Exception means every failure is invisible: if the CRM is down, the job still reports success, and because it catches Exception it also hides real bugs like a NullPointerException.

Then, if they want more

At minimum it needs logging with the customer id and metrics, and it should catch only the expected CRM exceptions. Second, findAll loads every customer as a managed entity at once; with two million customers that's gigabytes of heap plus Hibernate's snapshots, so it risks OutOfMemoryError.

I'd read in batches with keyset paging on the id, using a small projection instead of full entities.

Third, the @Transactional on the whole method keeps one transaction and one pooled connection open for the entire run, mostly waiting on HTTP calls; two million calls at fifty milliseconds is about twenty-eight hours, and in PostgreSQL a transaction that long also blocks vacuum. Remote calls should never be inside a transaction.

Fourth, there's no retry, no idempotency and no progress record, so a transient error drops a customer and a crash means starting from scratch.

My rewrite removes @Transactional, reads five hundred customers at a time, calls the CRM outside any transaction with an idempotency key or an upsert, retries transient failures with backoff, and records each customer's outcome in a short transaction, so the next run only retries failures and we can see the failure rate on a dashboard.

About this answer

Last updated
12 November 2026
Versions it names
Java 21, Spring Framework 7
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 "Review this code and list the problems:": https://scrivio-interview-library.netlify.app/java/clean-code/3c394cb5fe/