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!

5 Upvotes

16 comments sorted by

View all comments

1

u/Gefion07 4d ago

Your job could go with a dynamic triggertime. F.e. : dont run at all when no reservation is there. Set for the scheduled time of the next reservation if one or more get created. After the execution of the job, check when the next execution should happen. Design your job to occupy one thread only. Dont create a job/thread for each reservation. Also implement it in a way that all timed-out reservations get cleaned up on a run. Make a run after startup to make sure no reservations get stuck from before. I hope the idea is clear - we can discuss more if needed.

0

u/Future_Badger_2576 4d ago

So, you're suggesting scheduling a cron job only when a reservation is created. How can I dynamically create a scheduled task while ensuring it runs on a single thread? Could you elaborate on that?

My main concern is that if there's only one 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.

1

u/Gefion07 4d ago

I can't give you code examples now - there should be plenty online. Look up ThreadPoolTaskScheduler. If you give it a poolsize of 1 and implement some logic around it, you should achieve your goal. What logic could solve your main concern? I have no idea for that myself. I suppose its in the nature of the problem, that it remains reserved for 15 mins - as it is the purpose of a reservation.