Atomic Updates on MongoDB with Spring Data

MongoDB provides operators for atomic updates in addition to the normal insert and modify functionality. These operators include, $inc, $set and $unset; and are particularly useful for keeping counters and for thread-safe field updates, which helps resolve data-related concurrency issues in web and multi-threaded applications. If persistence is required and performance is not an issue, these operators can also be a good replacement for single-threaded caching solutions like Redis by providing persistent atomic operations. The use cases for using these operations include, real-time web analytics, leader boards, rate limiting etc.

Spring data provides simple constructs to easily perform these atomic operation on Mongo documents. Below is a sample document, so lets update it atomically.

Below is the Spring Data code snippet for querying and updating documents. The $inc operator is used to increment or decrement the field value. And $set updates the field value or adds a field in the document if it doesn’t exist. Similarly $unset operator removes the field from the document.

When the above update operation runs, the document will have “hits” incremented by 1, “lastAccess” set to current date and the “inactive” field removed. All of it thread-safe and atomic. And the resulting document will look something like below:

 

CAS and distributed Infinispan integration

CAS is a centralised authentication server that makes it very easy to implement single sign-on (SSO) in java application, and is a very good OAuth alternative. For distributed/clustered environments CAS also offers integration with a number of caching technologies in order to support single-logout (SLO). Recently we had an issue on clustered Wildfly J2EE servers where we had to support SLO in our distributed spring-boot based applications. Infinispan is the default distributed caching technology used by Wildfly, and unfortunately we didn’t find any integration support provided by CAS for Infinispan. So I wrote an integration library for CAS & Infinispan, which is available on github under Apache License. This library makes it possible to achieve SLO in distributed J2EE applications on Wildfly.

In order integrate CAS on the client side add the following dependency to the application’s POM file:

We then lookup the distributed Infinispan cache using JNDI and use it as storage for CAS tickets. Please see my previous post for more information on Infinispan and Spring boot integration.

With this CAS will use the distributed Infinispan on Wildfly to cache the authentication tickets. The authentication tickets are deleted on user logout. So now when the user logs out from one of the applications, deployed on Wildfly, he/she will be logged out from all the clustered applications; hence achieving single-logout (SLO).

For more information please see the CAS-Infinispan integration client on Github.