DEV Community

Shubham Bhati
Shubham Bhati

Posted on

Stop Holding DB Connections Hostage

We often throw @Transactional on Spring Boot service methods without thinking. If your method queries PostgreSQL, calls an external API and updates Redis, you hold that HikariCP database connection for the entire API call duration. On cheap servers, this kills performance fast.

HikariCP defaults to 10 connections. If 10 users hit a slow external API, your app freezes. Keep transactions tight.

// Bad: Connection held during slow API call
@Transactional
public void checkout(OrderDto dto) {
    Order order = repo.findById(dto.id());
    paymentService.charge(order); // Slow
    order.setStatus(PAID);
    repo.save(order);
}

// Good: Connection held only for DB write
public void checkout(OrderDto dto) {
    Order order = repo.findById(dto.id());
    paymentService.charge(order);
    updateStatus(order.getId());
}

@Transactional
public void updateStatus(Long id) {
    repo.updateStatus(id, PAID);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)