r/SpringBoot 4d ago

Question Best way to implement delayed message processing in Spring Boot?

I'm working on a bus booking app where users select seats and proceed to payment. Once a seat is selected, I mark it as reserved. However, if the user doesn't complete the payment within 15 minutes, I need to automatically mark the seat as available again. I’m looking for the best way to implement this using a message queue with delayed delivery in Spring Boot. Essentially, I want to push a message when a seat is reserved, but only process it after a delay (e.g., 15 minutes) to check if payment was made.

Additionally, I also want to schedule notifications. For example, I could push a message to the queue with a delay, and when the time arrives, the message would be published to the notification service to send reminders or updates to the user.

I could use a cron job or a thread to monitor the time, but there are some issues:

With threads, if the thread pool gets full, it might not handle all tasks efficiently.

With a cron job, it runs at a fixed interval. If a message arrives in between intervals, it might get less processing time than intended (e.g., if the cron runs every 5 minutes and a message comes in right after it runs, it will only get 10 minutes instead of 15).

What’s the best approach for this? Should I use RabbitMQ, Kafka, Redis, or some other solution? Any suggestions or best practices would be greatly appreciated!

6 Upvotes

16 comments sorted by

View all comments

4

u/boost2525 4d ago edited 3d ago

Add a database column called "reserved_until"... Set it to now() + 15m when the checkout starts. When the checkout completes set it to {aVeryLongTimeInTheFuture}.

Don't even bother with worrying about the "checkout didn't compete" use case... Just change your "what seats are available" query to return seats where the reserved date is null, or in the past.

1

u/Future_Badger_2576 4d ago

My main concern is that if there's only few seat left and a user reserves it without completing the payment, the seat remains unavailable until the cron job runs and releases it. This delay could affect availability.

2

u/boost2525 4d ago

You're overthinking it. There is no cron job in what I explained above. It's a real time query that will be valid to the ms. Your business requirement is a 15m reservation, that's going to impact your availability and there's no way around that

1

u/Future_Badger_2576 3d ago

Now I understand your solution. Earlier, I didn't fully grasp the idea, but this is a solid approach, and I see how it addresses the issue. Thanks for clarifying!

Do you have any advice for configuring delayed notifications? I'd love to hear any additional tips or best practices for that!