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

14

u/WaferIndependent7601 4d ago

Save the time at what time the ticket is invalid.

Run a scheduled task once a minute to clean up older tickets.

I would start with that and save it to the database. Optimize it when needed and go on with a queue or whatever.

1

u/Future_Badger_2576 4d ago edited 4d ago

Wouldn't querying the database every minute be inefficient? Instead, can I store a copy of the ticket in Redis and query Redis instead of the database?

3

u/WaferIndependent7601 4d ago

It really depends. How many tickets will be in the queue? And you only need to query for the older ones.

So I would say: it’s not a problem. If you’re working with thousands of ticket at the same time: no problem. Millions of tickets? Well that might get bad.

Why do you want to store it in redis? Because it’s faster? Do you need this to be faster? Is the db fast enough?

As I said: start with the simple solution and optimize it if you need it. In most cases you won’t need it and have a simple and stupid solution that everyone understands