Asynchronous task execution using Redis and Spring framework
TL;DR:
In this article, we are going to see how to use Spring boot 2.x and Redis to execute asynchronous tasks, with the final code that we will have after following the steps described here.
Spring/Spring Boot
Spring is the most popular framework available for the Java platform. Spring has one of the largest communities in open source. Besides that, Spring provides extensive and up-to-date documentation that covers the inner workings of the framework and sample projects on their blog, there’re 100K+ questions on StackOverflow.
Spring 3.0 was the first version that supported the annotation-based configuration, later in 2014 Spring boot 1.0 was released that completely changed how we look at the Spring framework ecosystems, it provides out of the box configuration and many more. Timeline
Redis
Redis is one of the most popular open-source NoSQL in-memory database. Redis supports different types of data structures e.g. Set, Hash table, List, simple key-value pair just name a few. The latency of Redis call is sub-milliseconds, support of a replica set, etc.
Why Asynchronous task execution
A typical API call consists of five things
- Execute one or more database(RDBMS/NoSQL) queries
- One or more operations on some cache systems (In-Memory, Distributed, etc )
- Some computations (it could be some data crunching doing some math operations)
- Calling some other service(s) (internal/external)
- Schedule one or more tasks to be executed at a later time or immediately but in the background.
A task can be scheduled at a later time for many reasons for example invoice must be generated after 7 days of order creation or order shipment, similarly, email/notification(s) need not be sent immediately it can be delayed. Sometimes we need to execute tasks in asynchronous to reduce API response time, for example, delete 1K+ records at once if we delete all these records in the same API call then API response time would be increased for sure, to reduce API response time, we can run a task in the background that would delete those records.
Delayed queue
We can run schedule tasks using cron jobs, a cron job can be scheduled using different methods like UNIX style crontabs, Chronos, if we’re using Spring frameworks then it’s out of box Scheduled annotation ❤️. Most of these scheduling mechanisms suffer scaling problems, where we do scan database(s) to find the relevant rows/records. In many of the situations, this leads to a full table scan which performs very poor. Imagine the case where the same database is used by a real-time application and this batch processing system. A delayed queue can be used in such cases where as soon as the timer reaches the scheduled time a job would be triggered. There’re many queuing systems/software available but very few of them provides this feature, like SQS which provides a delay of 15 minutes, not an arbitrary delay like 7 hours or 7 days, etc.
Rqueue
Rqueue is a broker built for the spring framework that stores data in Redis and provides a mechanism to execute a task at any arbitrary delay. Rqueue is backed by Redis since Redis has some advantages over the widely used queuing systems like Kafka, SQS. In most of the web applications backend, Redis is used to store either cache data or for some other purpose. In today's world, 8.4% web applications are using the Redis database.
Generally, for a queue, we use either Kafka/SQS or some other systems these systems bring an additional overhead in different dimensions e.g money which can be reduced to zero using Rqueue and Redis.
Apart from the cost if we use Kafka then we need to do infrastructure setup, maintenance i.e. more ops, as most of the applications are already using Redis so we won’t have ops overhead, in fact, same Redis server/cluster can be used with Rqueue. Rqueue supports an arbitrary delay

Message Delivery
Rqueue guarantee at-least-once message delivery as long data is not lost in the database. Read about it more at Introducing Rqueue
Tools we need:
1. Any IDE 2. Gradle 3. Java 4. Redis
We’re going to use Spring boot for simplicity, we’ll create a Gradle project from spring boot initializer at https://start.spring.io/, for dependency we would need 1. Spring Data Redis 2. Spring Web 3. Lombok and any others. The directory/folder structure would look like below.

We’re going to use the Rqueue library to execute any tasks with any arbitrary delay. Rqueue is a Spring-based asynchronous task executor, that can execute tasks at any delay, it’s built upon the Spring messaging library and backed by Redis.
We’ll add the dependency of Rqueue spring boot starter with com.github.sonus21:rqueue-spring-boot-starter:1.2-RELEASE
We need to enable Redis spring boot features, for testing purposes we will enable WEB MVC as well.
Update Application file as
Adding tasks using Rqueue is very simple we need to just annotate a method with RqueueListener. RqueuListener annotation has few fields that can be set based on the use-case. For delayed tasks, we need to set delayedQueue=”true” and value must be provided otherwise it’ll be ignored, value is the name of a given queue. Set deadLetterQueue to push tasks to another queue otherwise task will be discarded on failure. We can also set how many times a task should be retried using the numRetries field.
Create a Java file name MessageListener and add some methods to execute tasks.
We would need Email and Invoice classes to store email and invoice data respectively. For simplicity, classes would only have a handful number of fields.
Invoice.java
Email.java
Task submissions
A task can be submitted using RqueueMessageSender bean. This has multiple methods to put a task depending on the use case, like for retry use method having retry count, delay for delayed tasks.
We need to AutoWire RqueueMessageSender or use constructor based injection to inject this beans
Create a Controller for testing purpose:
We’re going to schedule invoice generation that would be done in the next 30 seconds, for this we’ll submit a task with 30000 (milliseconds) delay on invoice queue. Also, we’ll try to send an email that will be done in the background. For this purpose, we’ll add two GET methods sendEmail and generateInvoice, we can use POST as well.
Add the following in application.properties file
Now we can run this application, once the application starts successfully, browse
In the log, we can see tasks are being executed in the background

Invoice scheduling after 30 seconds
http://localhost:8080/invoice?id=INV-1234&type=PROFORMA

In conclusion, we can schedule tasks using Rqueue without much of the boiler code. We need to consider a few things while configuring the Rqueue library and using them. One of the important is whether a task is a delayed task or not; by default, it’s assumed tasks need to be executed as soon as possible.
Complete code can be found at my Github account https://github.com/sonus21/rqueue-task-exector
Rqueue library code: https://github.com/sonus21/rqueue
If you found this post helpful please share across and give a thumbs up.
