Video in progress

Strong Middle 🧵 Concurrency

This Spring service works fine in tests, but in prod it sometimes returns another customer's data. Why?

@Service
public class InvoiceService {
    private User currentUser;          // instance field
    private final InvoiceRepository repo;

    public InvoiceService(InvoiceRepository repo) { this.repo = repo; }

    public List<Invoice> myInvoices(User user) {
        this.currentUser = user;
        audit("ro'yxat so'raldi");
        return repo.findByOwner(currentUser.id());
    }

    private void audit(String msg) { /* writes a log line with currentUser */ }
}

Spring beans are singletons by default, so one object is shared by all request threads. Because currentUser is an instance field, concurrent requests overwrite each other's value. Request-specific state has to live in a parameter or a local variable.

📖 Answer

In a test there is only one thread, so everything is fine. In prod, Tomcat's 200 threads all enter the same InvoiceService object:

T1: currentUser = Ali
T2: currentUser = Vali
T1: repo.findByOwner(currentUser.id())   // Vali's invoices went to Ali

This is a plain race condition, but the consequence is a data leak, which makes it a security incident. And it only shows up under load, and rarely.

The fix is to remove the state from the field:

public List<Invoice> myInvoices(User user) {
    audit(user, "ro'yxat so'raldi");
    return repo.findByOwner(user.id());
}

The rule: in a singleton bean, fields are only for things that never change: other beans, configuration, thread-safe clients (final, set through the constructor). Everything that belongs to a request is a parameter or a local variable.

@RequestScope is also an option, but it's often unnecessary complexity. Adding synchronized is the wrong way: it lines all requests up in a single queue.

Similar hidden state: a SimpleDateFormat, a StringBuilder or a plain HashMap cache in a field. In code review, a non-final field in a @Service/@Component class is an immediate question for me.