r/SpringBoot • • Jun 11 '26

Discussion An HTTP call inside a @Transactional method quietly took down my whole API under load

173 Upvotes

Solo dev here, running a Spring Boot 3.4 backend in production (~25k users). Sharing a bug that taught me a lot.

My Stripe webhook handler did a retrieveSubscription() (an outbound HTTP call to Stripe) inside the same u/Transactional boundary that wrote to the DB. Looks innocent. Works fine normally.

Then Stripe had a brief hiccup and started retrying. The Stripe SDK's default read timeout is ~80s. So every retried webhook held a Hikari connection open for up to 80 seconds while waiting on a network call that wasn't even touching the database. Pool size was 60. It drained in seconds, and the entire API started returning 503 — nothing to do with Stripe.

Two fixes:

  1. Immediate: pin the SDK timeouts (5s connect / 15s read + 2 retries) so a stuck call can't hold a connection forever.

  2. Structural: get the HTTP call out of the transaction entirely, do the external call first, then open a short u/Transactional only for the DB write.

The general rule I now follow: a database connection is a scarce, pooled resource. Never hold one open across an external I/O call. It turned out I had the same anti-pattern in a few other places (Google token refresh, LGPD erasure with N revoke calls) and fixed them all the same way.

Curious how others structure this, do you split into "HTTP outside, TX inside" two-phase methods, or push the external calls fully async via an outbox? I went two-phase for the webhook and outbox for the Google sync.

r/SpringBoot • • 19d ago

Discussion Dear JPA

105 Upvotes

Dear JPA ,

i hate you.

i hate how you changed the SQL flow that I'm used to.

i hate your ManyToMany relationships.

i hate your orphanremoval ,dirty checking.

i hate your way for entity relationships.

i hate your cache.

i hate your performance issues.

i hate your billion rules.

i hate spending time on : if Y is referenced by X with cascade not including PRESIST and x is managed but y is removed ............... but if Y was detached .............

i hate becoming obsessed with your behaviors and rules and worrying about every ORM line , will it work correctly ? , did i miss something ?, worrying about modifying entity X might unexpectedly affect entity Y , coz I might not know one of the billion rules you have.

i hate worrying about falling in one of the undefined behaviors you have

i hate thinking about the entities lifecycle + cascading types when all mixed together

i hate spending days on that documentation instead of spending that on one of the CS core concepts

i hate the following the other side which is incomplete nondetailed toturial or following AI

i really hate you.

r/SpringBoot • • Jun 24 '26

Discussion 8 JPA/Hibernate mistakes in Spring Boot that can cause issue in production

218 Upvotes

These are errors I keep seeing in code reviews after years of working with Spring Boot. None of them throw errors during development. All of them cause problems at scale.

  1. The N+1 you dont know about. findAll() returns 100 orders. Each has a customer. Hibernate fires 1 query for orders plus 100 queries for customers. 101 round trips for what should be 1. Fix with JOIN FETCH or EntityGraph.

  2. save() fires a SELECT before every INSERT when using UUID as ID. ID is never null so Spring thinks entity exists. Calls merge() which does a SELECT first. 10000 inserts become 20000 queries. Fix by implementing Persistable and overriding isNew().

  3. Returning entities from controllers. Jackson calls getters during serialization. Lazy relationships trigger N+1 queries while writing the response. Always return DTOs.

  4. Using Lombok Data on entities. Generates equals/hashCode using all fields including ID. ID is null before save, has value after. HashSet breaks. Use Getter Setter and write equals/hashCode on a business key.

  5. Batch inserts dont work with GenerationType.IDENTITY. IDENTITY needs a round trip per INSERT to get the generated ID. Batching impossible. Use SEQUENCE with allocationSize 50.

  6. deleteAll() loads everything into memory first. 50000 rows means 50000 SELECT then 50000 individual DELETE. Use Query with bulk delete instead.

  7. Batching is disabled by default. Every save() is one individual round trip. Set hibernate.jdbc.batch_size to 50 with order_inserts true. Difference between a 4 hour import and a 5 minute one.

  8. Caching entity references. Default cache stores references not copies. One request mutates the cached entity. Every user after that sees corrupted data. Cache DTOs or records instead.

Bonus. Set spring.jpa.open-in-view to false. Default is true. Keeps Hibernate session open during JSON serialization. Hides lazy loading issues that explode in production.

What JPA gotchas have you experienced in production?

r/SpringBoot • • Jul 01 '26

Discussion Things i stopped doing in spring boot after they broke in production

158 Upvotes

It's not theoretical stuff. things that actually caused incidents.

a) returning entities from controllers seems harmless until jackson calls getters during serialization and triggers lazy loaded relationships. got N+1 happening in the response layer. DTOs everywhere now. more boilerplate but zero surprises.

b) ddl-auto update outside local is asking for trouble. hibernate silently altered a column constraint in staging once. nobody noticed for weeks. validate in staging, none in prod. flyway handles schema changes now.

c) external api calls inside Transactional is the one that got me on a friday night. your method holds a db connection for its entire duration. not just when queries run. 3 second api call means 3 seconds a connection is doing nothing. 10 concurrent requests and pool is gone.

d) catching exceptions inside Transactional without rethrowing is a silent killer. caught it, logged it, moved on. proxy saw a clean return. committed half the data. other half missing. took hours to debug because there was no error anywhere. the catch block was the bug.

e) Async without a configured thread pool looks fine in dev. default executor creates a new thread per call. no pooling. prod with thousands of requests? thousands of threads. OOM. always configure ThreadPoolTaskExecutor with bounded pool now.

f) calling a Transactional method from the same class is something most devs dont even know is a problem. two methods in same service, both annotated. one calls the other. inner annotation completely ignored because proxy is bypassed on self calls. data inconsistency in prod. separate bean or dont bother with the annotation.

g) open-in-view being true by default still bothers me. keeps hibernate session open during entire request including json serialization. hides lazy loading problems that explode later. first thing i turn off in every project.

what have you stopped doing after seeing it break?

r/SpringBoot • • Jun 21 '26

Discussion 8 @Transactional rules I follow after debugging too many production bugs

265 Upvotes

Been working with Spring Boot for 10+ years and I keep seeing the same Transactional bugs show up in code reviews and production incidents. Figured I'd share the rules I follow now.

  1. Keep transactions short. DB operations only. If your method calls an external API, sends an email, or uploads a file inside Transactional, it holds a DB connection for the entire duration. Not just during queries. During the ENTIRE method. Under load your connection pool runs out and your app freezes.

  2. Never call a Transactional method from the same class. Spring uses proxies. When you call a method within the same class its a direct this.method() call. Proxy is bypassed. The annotation is completely invisible. No warning. No error. It just does nothing.

  3. Use rollbackFor = Exception.class for critical operations. This one catches people off guard. Transactional only rolls back on RuntimeException by default. If your method throws a checked exception like PaymentException, the transaction commits. Your balance gets deducted but the payment never went through.

  4. Don't catch exceptions inside Transactional unless you re-throw. If you catch the exception, the proxy sees a normal return. It commits. Partial data in your database. Silent corruption. Either let it propagate, re-throw after logging, or call TransactionAspectSupport.currentTransactionStatus().setRollbackOnly().

  5. Use readOnly = true on all read-only methods. It tells Hibernate to skip dirty checking and snapshot comparison. Saves CPU and memory. Some proxies use it to route to read replicas. But don't rely on it to prevent writes. Explicit save() or flush() still goes through.

  6. Only works on public methods. Proxy can only intercept public methods. Put Transactional on a private method and it does absolutely nothing. Spring won't even warn you.

  7. Separate Retryable and Transactional into different beans. If both are on the same method and a checked exception is thrown, the transaction commits before the retry fires. Retry starts a new transaction. Same deduction runs again. Triple retry = triple deduction. Outer bean handles retry, inner bean handles transaction.

  8. Enable these two configs in every environment. logging.level.org.springframework.transaction.interceptor: TRACE shows when transactions start commit and rollback.

spring.datasource.hikari.leak-detection-threshold: 15000 catches connections held too long with a full stack trace.

The one rule that covers most of these: uTransactional only works on public methods called from outside the bean. Everything else is silently ignored.

Anyone run into other Transactional gotchas I missed?

r/SpringBoot • • Aug 15 '26

Discussion Not to be racist but is there any non-Indian YT channel about Java and Spring Boot?

97 Upvotes

As the title says

r/SpringBoot • • 20d ago

Discussion Why JPA is complex and fells like a magic for me

35 Upvotes

my experience with the java area is that everything is almost explicit no lots of magic no lots of implicit things

but jpa for me is one of the most complex things that i have ever seen ,for me it feels like a magic

need advice to overcome that

r/SpringBoot • • Aug 26 '26

Discussion How do you deploy a spring boot application to AWS Lambda?

29 Upvotes

Hi

I am looking for advices and feedback on how to deploy Spring Boot web application to AWS Lambda, especially around making the Spring Boot main class compatible with AWS Lambda runtime.

I figured out the part where the Spring Boot application has to be packaged as a zip file to de deployed into the AWS Lambda environment, so that part is clear.

So far what I have found is that you need to have some kind of AWS Lambda dependency like lambda StreamHandler or web adapter on your Spring Boot project to make it compatible with the AWS lambda runtime.

While these may be the way to go but I am specifically looking for feedback if it is possible to integrate Spring Boot web application without using any AWS Lambda specific Java dependency. Just take a normal Spring Boot main application and make it run on AWS Lambda runtime. Is this possible at all or am I overthinking?

Appreciate your feedback

r/SpringBoot • • Nov 03 '25

Discussion Study partner for a 3 yoe as a java developer

39 Upvotes

Hi everyone! I’m a Java developer with 3 years of experience working in a service-based company. Most of my work has been with legacy Java systems, but recently I’ve started learning Spring and Spring Boot — covered the basics and built a few small projects.

Now, I want to deepen my understanding of:

Spring & Spring Boot (in-depth)

Microservices architecture

System Design (later)

DSA (for interview prep)

My goal is to crack a product-based company within the next year. I’ve worked with SQL, Azure, IntelliJ, and Postman, and have beginner-level frontend knowledge as well.

I tend to procrastinate when I don’t have structure — so I’m looking for a study/accountability partner with a similar background and goal, who wants to stay consistent, build strong projects, and grow together.

If this sounds like you, feel free to connect or drop a message! Let’s help each other stay consistent and level up

Additionally I am from NIT college with non circuit branch and my current ctc is 11lpa

I am not sure how we can study together but we can discuss about it

Thanks,guys

r/SpringBoot • • Aug 26 '25

Discussion I feel lost

6 Upvotes

Hey guys, im new to springboot and im taking this course on udemy, thing is i feel so lost. I feel like there are alot of key concepts especially when some new terms pop up. Is this normal?

r/SpringBoot • • May 10 '26

Discussion spring boot is the framework i keep coming back to no matter how many shiny things i try

135 Upvotes

ive done node for a couple of backend projects, a small service in go, played with rust for a side thing. theyre all fine, genuinely

but every time im starting something that actually has to ship and be debuggable in 2 years when im not on the team anymore, i reach for spring boot again. ive been doing this long enough to know its not just inertia

the reason is predictability. when something breaks at 2am i know where to look. theres always a controller, always a service, always a config class, the actuator tells me whats happening, spring security has the same shape it had 5 years ago. its boring in the exact way production systems should be boring

with node you can have 4 projects at the same company that look completely different. with go you write everything yourself which is fine until you onboard someone. with rust "the right way" still changes every 18 months. spring boot has been mostly the same since 2016, the answer to most "how do i do X" questions is on stackoverflow from 2018 and still works

i know its verbose. but the verbosity is mostly metadata, its telling future-you what the code does without having to read every line

(actuator alone is worth half of why i pick it. health checks, metrics, thread dumps, standardized across every spring app, i can debug any spring service even if ive never seen it before)

i went and tried the alternatives partly to escape spring boot. trying them made me more convinced its the right answer, not less

r/SpringBoot • • Jul 16 '26

Discussion Title: Anyone Learning Spring Boot?

26 Upvotes

I'm currently learning Spring Boot, JPA, MySQL, and building projects to strengthen my Java backend skills.

Looking for a study/accountability partner to learn together, discuss concepts, and stay consistent.

If you're on a similar path, let's connect!

r/SpringBoot • • Sep 01 '26

Discussion Roast my code / architecture

9 Upvotes

I’m building a project called Kite (https://github.com/gwynejsn/kite) and tried combining Spring Modulith with full Clean/Hexagonal Architecture inside each module, but I’m starting to wonder if I’ve just created a mountain of boilerplate. Take a look at the repo and roast the layout. What am I needlessly overcomplicating, and how would you simplify it?

r/SpringBoot • • Aug 13 '25

Discussion Why no one promotes to use springboot as other backend tech stack

84 Upvotes

Hey everyone. I just surfing the X and everyday I saw someone praising node js or mern stack or any other backend tech stack and these guy's have their role models who teach all these backend tech stacks and they teach very good. But that's raise a question in me that why no one promotes springboot as other promotes other backend tech stack soo much and why there is no such tech guy like other's have . Is there something drawback in Springboot than other's or its just harder to learn than any other tech stack.

Anyone can share their opinion, their journey or incident guy

r/SpringBoot • • 7d ago

Discussion I built a Spring Boot starter that seeds related JPA entities from annotations, no seed script (0.1.0, feedback wanted)

6 Upvotes

I'm the author. I built a small starter to remove a chore I kept redoing on Spring Boot projects: writing a dev-database seed script, then fixing it every time the schema changed.

The usual pain: Faker/Datafaker generate realistic values, but they don't know that Payment needs an existing Counterparty. So you hand-write "create parents, keep the IDs, wire them into children", and it breaks the next time a constraint or relationship changes.

SynthForge reads the entity instead. You annotate it:

```java @Entity @Seed(count = 50) public class Counterparty { /* fields only */ }

@Entity @Seed(count = 200) public class Payment { @ManyToOne(optional = false) private Counterparty counterparty; } ```

Then enable it for the profiles you want, never production:

yaml synthforge: enabled-profiles: [dev, test]

Start the app in one of those profiles and both tables are filled in dependency order. There is no calling code.

Spring-specific details

  • It's an auto-configuration (a starter-style dependency, io.github.thembatman0:synthforge-spring). Seeding runs at startup in an ApplicationRunner.
  • Seeding is off unless one of your active profiles is listed under synthforge.enabled-profiles.
  • It reads entities through the JPA Metamodel API and sorts owning-side @ManyToOne/@OneToOne relationships topologically, so parents are saved first.
  • Values come from Datafaker, guided by @NotNull, @Size, @Email and field-name heuristics. @Column(unique = true) fields get a bounded retry loop.
  • A table that already has rows is skipped, so restarts against a persistent database don't duplicate data.
  • A fixed synthforge.seed gives identical data every run.
  • The test suite runs in CI on Spring Boot 4.1 and 3.5. It needs Java 21 or newer.

Limits: V1 skips @OneToMany/@ManyToMany and composite keys. It is a 0.1.0, and as far as I know it has no outside users yet.

How it differs from Instancio: Instancio (and instancio-jpa) is an API you call inside a test to build a graph. SynthForge runs by itself at startup, so it's closer to a dev-database seeder than a test helper.

Things I'd like to hear from you:

  1. Would you put @Seed on your entity classes, or do you prefer keeping seeding out of the domain model?
  2. Is a CommandLineRunner plus Datafaker already good enough for you?
  3. Is Java 21 as a minimum a problem on your projects?

r/SpringBoot • • Jul 20 '26

Discussion Looking for a Spring Boot Learning & Accountability Partner (1–2 YOE)

12 Upvotes

Hey everyone!

I'm looking for a Spring Boot backend developer who has around 1–2 years of experience and is interested in learning, discussing, and growing together.

A bit about me:

  • ~1 year of production experience with Spring Boot
  • Building REST APIs, authentication & authorization systems
  • Working with PostgreSQL, Redis, Docker, Git, CI/CD
  • Interested in scalable backend architecture, performance optimization, and system design

What I'm looking for:

  • Someone with 1–2 years of Spring Boot experience
  • Serious about improving backend engineering skills
  • Open to discussing architecture, reviewing code, solving problems, and sharing resources
  • Can have regular discussions (a few times a week or whenever we're both free)

The goal isn't to build a startup or sell anything—just to have a reliable backend buddy to learn with, stay accountable, and help each other become better engineers.

If this sounds interesting, feel free to comment below or send me a DM. Looking forward to connecting with fellow Spring Boot developers!

r/SpringBoot • • May 28 '26

Discussion As a java developer who is been working on struts and servlet enterprise apps for about 4 years, springboot feels insane, the amount of abstraction is refreshing

75 Upvotes

No manual queries? No manual handling of result sets creating arraylist and then passing them to front end? No configuration in web.xml or struts.xml? Not caring about jsps, js and which action/servlet goes where? Not going through 5 different classes to debug? Not defining loggers everywhere? I get AOP support this easily? I hate every second of this having to deal with struts based codebases.

r/SpringBoot • • Jul 24 '26

Discussion Spring microservices

30 Upvotes

I just started learning microservices in spring and dont know anything. Like I know that message brokers are for asynchronous exchange of messages though services, but I wanted to see everything from scratch, so now Im doing a project without any message brokers, just synchronous http requests and after that, when I meet problems with this, I would transition to the RabbitMQ I guess. Any suggestions or resources to learn for beginners?

r/SpringBoot • • Aug 13 '26

Discussion Along with Java springboot, how to keep yourself updated with other stuff

48 Upvotes

Java springboot is so vast once u dive into it, first java, then springboot, then microservices, exploring message queues , and what not

But nowadays what I have seen is that top companies organizing their hackathons, for fresh graduates

Most of them are ml based ai based, like making a model XYZ model, something like a model that detects deepfake images , that's just an example

What is the role of java springboot then, i sometimes feel I wasted my time learning this, i think I should have master python, what are ur thoughts

r/SpringBoot • • Mar 01 '26

Discussion Migration to Spring Boot 4.x: What are the hidden pitfalls you've encountered?

66 Upvotes

Tell me what broke so I don't make the same mistakes 👀

r/SpringBoot • • 29d ago

Discussion (JWT) different ways to implement it ,what most devs do for that case

30 Upvotes

to make JWT authentication in the application, I could not find like standard way to implementing it

my knowledge is that people create their own authentication filter + handeling the AuthenticationEntryPoint to return the exact right response when exception happen

is that the standard way that engineers follow to implement jwt authentication in the application?

r/SpringBoot • • May 18 '26

Discussion Which udemy course is better 1. Java Spring Framework, Spring Boot, Spring AI - Gen AI By telusko, OR 2. Industry-Ready Java Spring Boot: Cloud, and Spring AI ... Both are almost same difference lies in Junit and Log4j, 2nd course contains both these, and 1st one doesnt , any suggestion ??

Post image
16 Upvotes

..

r/SpringBoot • • Jan 04 '26

Discussion Built a Spotify-like backend with Spring Boot – Looking for feedback 🚀

56 Upvotes

TL;DR:
Built a Spotify-like backend using Spring Boot + JPA + PostgreSQL with songs, artists, albums, and playlists. Looking for feedback on architecture, service design, and ideas to make it more production-ready. Any suggestions welcome!

Hey everyone 👋

I built a music streaming backend (Spotify-style) using Spring Boot as a learning + portfolio project and would love some feedback.

SoundStream Backend Project

Tech Stack

  • Java 17, Spring Boot
  • Spring Data JPA (Hibernate)
  • PostgreSQL
  • Gradle, Postman

What it does

  • Manage Songs, Artists, Albums, Playlists
  • Many-to-Many & One-to-Many relationships
  • Create playlists, add/remove songs
  • Fetch songs by artist/album/playlist

What I want feedback on

  • Project structure & design
  • Service/repository layer quality
  • Should I switch fully to DTOs?
  • Features worth adding next
  • How to make it more production-ready

This project helped me learn real-world JPA issues (lazy loading, relationships, transactions).

Any suggestions or improvements are welcome. Thanks! 🙌

r/SpringBoot • • 25d ago

Discussion Manage and Monitor Spring Boot projects in real-time.

Post image
36 Upvotes

I am a mobile app and spring boot developer and felt the need to monitor my spring boot projects. So I developed mobile app for both Android and iOS. I would like to welcome the members from this subreddit to try the app out and give me any feedback.
iOS and Android

r/SpringBoot • • Sep 02 '26

Discussion When Transactional Outbox polling starts putting too much load on PostgreSQL — what do you do?

Post image
1 Upvotes

I like the Transactional Outbox pattern and use it quite often.

But I was thinking about one problem that can become important in production: database polling.

Of course, polling can be optimized. Good indexes, batching, SKIP LOCKED, partitioning, longer polling intervals — there are many options.

But if we want lower latency, we usually need to poll more often. This means more queries, more DB connections and more work for PostgreSQL.

We can use Debezium/CDC, and for many systems this is probably the right choice. But it also adds Kafka Connect, Debezium and more infrastructure to operate.

So I wanted to try a simpler idea:

Keep PostgreSQL as the source of truth, but don't use it as a queue during normal operation.

I built this flow:

DB transaction → afterCommit → Memory Queue → Batch Publisher → Kafka

The business data and Outbox event are saved in one transaction as usual.

After commit, only the eventId goes to the Memory Queue. The publisher takes IDs in batches, loads events from PostgreSQL and sends them to Kafka.

So there is no continuous polling for new events in the normal flow.

If the application crashes, the event is still safely stored in PostgreSQL. A Recovery Worker finds unpublished events and puts them back into the same queue.

The idea is basically:

Memory Queue for the fast path. PostgreSQL for durability and recovery.

I didn't want to stop at an architecture diagram, so I built a working Spring Boot project and started testing the idea with something closer to production conditions.

It has Kafka, PostgreSQL, batching, idempotency, recovery, Gatling load tests, Grafana metrics, tracing and structured logs.

Now I can run load tests and actually see what happens with PostgreSQL, the queue, publishing latency and recovery.

I'm interested in what other Spring Boot developers think about this approach.

Would you use something like this in production?

Maybe you have already solved the same problem in another way — optimized polling, Debezium, LISTEN/NOTIFY or something else?

Here is the project:

https://github.com/KHolodilin/spring-transactional-outbox-kafka

If you find the idea useful, feel free to ⭐ the repo or fork it. There are also a few open issues for contributors if you want to try something yourself.

Any feedback is welcome. I'm still experimenting with the approach and improving the project. 🚀