Skip to main content

Deep Dive Test Automation of Spring Boot Application

· 8 min read

Testing Spring Boot applications is crucial for validating functionality across the persistence, service, and controller layers, especially when deployed in containerized environments. This guide covers everything from configuring each layer’s tests to handling parallel endpoint testing and leveraging Docker for containerized environments.



1. Overview​

Testing a Spring Boot application ensures each layer functions as expected and that the system performs cohesively. Tests should cover:

  • Persistence Layer: Verifying data access and manipulation.
  • Service Layer: Ensuring business logic functions correctly.
  • Controller Layer: Testing API endpoints and interactions.

This article includes testing strategies for both development and containerized environments, plus configurations for parallel endpoint testing.


2. Testing the Persistence Layer​

The persistence layer involves data storage and access. To test without connecting to production databases, use embedded databases for unit testing and Testcontainers for more complex integration tests.

Embedded Database for Testing​

Embedded databases (like H2) are ideal for simple, fast tests:

  1. Add H2 dependency in pom.xml:

    <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
    </dependency>
  2. Application configuration for testing (src/test/resources/application-test.yml):

    spring:
    datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
    username: sa
    password:
    jpa:
    hibernate:
    ddl-auto: create-drop
    show-sql: true
  3. Persistence Layer Test:

    @SpringBootTest
    @Transactional
    public class UserRepositoryTest {
    @Autowired
    private UserRepository userRepository;

    @Test
    public void testSaveUser() {
    User user = new User("John Doe", "john.doe@example.com");
    User savedUser = userRepository.save(user);
    assertNotNull(savedUser.getId());
    }
    }

Integration Testing with Testcontainers​

For more realistic integration tests with databases (e.g., PostgreSQL), use Testcontainers:

  1. Add Testcontainers dependency:

    <dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>postgresql</artifactId>
    <version>1.16.2</version>
    <scope>test</scope>
    </dependency>
  2. Set up Testcontainers for PostgreSQL:

    @SpringBootTest
    public class UserRepositoryTest {

    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:13")
    .withDatabaseName("testdb")
    .withUsername("user")
    .withPassword("password");

    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry) {
    postgres.start();
    registry.add("spring.datasource.url", postgres::getJdbcUrl);
    registry.add("spring.datasource.username", postgres::getUsername);
    registry.add("spring.datasource.password", postgres::getPassword);
    }

    @Autowired
    private UserRepository userRepository;

    @Test
    public void testFindUserById() {
    // Test logic
    }
    }

3. Testing the Service Layer​

The service layer holds business logic. Use mocks for isolated unit tests and real dependencies for integration tests.

Unit Tests with Mocks​

  1. Define a test with @MockBean:
    @ExtendWith(MockitoExtension.class)
    public class UserServiceTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @Test
    public void testCreateUser() {
    User user = new User("Alice", "alice@example.com");
    when(userRepository.save(any(User.class))).thenReturn(user);

    User savedUser = userService.createUser(user);
    assertEquals("Alice", savedUser.getName());
    }
    }

Integration Testing with Dependencies​

For full service layer integration:

@SpringBootTest
@Transactional
public class UserServiceIntegrationTest {

@Autowired
private UserService userService;

@Test
public void testFindAllUsers() {
List<User> users = userService.findAllUsers();
assertNotNull(users);
}
}

4. Testing the Controller Layer​

Controller tests validate API endpoints. MockMvc is used for isolated testing, while containerized setups allow testing real endpoints.

MockMvc for Isolated Controller Testing​

MockMvc allows API testing without starting a full web server.

@WebMvcTest(UserController.class)
public class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private UserService userService;

@Test
public void testGetUser() throws Exception {
when(userService.getUserById(anyLong())).thenReturn(new User(1L, "Alice"));

mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Alice"));
}
}

Testing Real Endpoints in a Container​

For real endpoint testing, use RestTemplate with a server running on a random port:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerIntegrationTest {

@LocalServerPort
private int port;

@Autowired
private TestRestTemplate restTemplate;

@Test
public void testGetUser() {
ResponseEntity<User> response = restTemplate.getForEntity("http://localhost:" + port + "/users/1", User.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
}
}

Parallel Testing for API Endpoints​

When testing multiple endpoints simultaneously, use RANDOM_PORT to prevent port conflicts.


5. End-to-End Testing in Containerized Environments​

Using Docker Compose, spin up services to perform full integration tests in a controlled environment.

Using Docker Compose for Integration Testing​

  1. Docker Compose File:

    version: '3'
    services:
    app:
    image: my-spring-app:latest
    ports:
    - "8080:8080"
    environment:
    - SPRING_PROFILES_ACTIVE=test
    postgres:
    image: postgres:13
    environment:
    POSTGRES_USER: user
    POSTGRES_PASSWORD: password
    POSTGRES_DB: testdb
  2. Run and Tear Down Tests:

    docker-compose up -d
    # Run integration tests
    docker-compose down

6. Sample Code and Configuration Summary​

This section provides practical code snippets and configurations to help automate testing in Spring Boot applications. The examples cover the persistence layer, service layer, controller layer, and containerized testing.

Maven Dependencies​

Make sure to include the necessary dependencies in your pom.xml for testing:

<dependencies>
<!-- Spring Boot Starter for Testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!-- H2 Database for In-Memory Testing -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>

<!-- Testcontainers for Integration Testing -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.16.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.16.2</version>
<scope>test</scope>
</dependency>
</dependencies>

Sample Application Properties​

Define properties for the test environment in src/test/resources/application-test.yml:

spring:
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password:
jpa:
hibernate:
ddl-auto: create-drop
show-sql: true

Persistence Layer Test Example​

Example of testing a repository with an embedded H2 database:

@SpringBootTest
@Transactional
public class UserRepositoryTest {

@Autowired
private UserRepository userRepository;

@Test
public void testSaveUser() {
User user = new User("John Doe", "john.doe@example.com");
User savedUser = userRepository.save(user);
assertNotNull(savedUser.getId());
}
}

Service Layer Test Example​

Example of unit testing the service layer with Mockito:

@ExtendWith(MockitoExtension.class)
public class UserServiceTest {

@Mock
private UserRepository userRepository;

@InjectMocks
private UserService userService;

@Test
public void testCreateUser() {
User user = new User("Alice", "alice@example.com");
when(userRepository.save(any(User.class))).thenReturn(user);

User savedUser = userService.createUser(user);
assertEquals("Alice", savedUser.getName());
}
}

Controller Layer Test Example​

Example of testing a controller using MockMvc:

@WebMvcTest(UserController.class)
public class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private UserService userService;

@Test
public void testGetUser() throws Exception {
when(userService.getUserById(anyLong())).thenReturn(new User(1L, "Alice"));

mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Alice"));
}
}

Integration Testing with Testcontainers​

Example of a test that uses Testcontainers to spin up a PostgreSQL instance for integration tests:

@SpringBootTest
public class UserRepositoryIntegrationTest {

static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:13")
.withDatabaseName("testdb")
.withUsername("user")
.withPassword("password");

@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
postgres.start();
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}

@Autowired
private UserRepository userRepository;

@Test
public void testFindUserById() {
User user = new User("Alice", "alice@example.com");
userRepository.save(user);

Optional<User> foundUser = userRepository.findById(user.getId());
assertTrue(foundUser.isPresent());
assertEquals("Alice", foundUser.get().getName());
}
}

Docker Compose Configuration​

An example of a docker-compose.yml file for running your application and PostgreSQL for testing:

version: '3.8'
services:
app:
image: my-spring-app:latest
ports:
- "8080:8080"
environment:
SPRING_PROFILES_ACTIVE: test
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/testdb
SPRING_DATASOURCE_USERNAME: user
SPRING_DATASOURCE_PASSWORD: password

postgres:
image: postgres:13
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: testdb

Running Tests in Docker​

Run your integration tests with Docker Compose:

docker-compose up -d
# Run tests
mvn test
docker-compose down

This guide offers configurations and code samples to help set up automated testing for Spring Boot applications in both development and containerized environments, suitable for integration into CI/CD pipelines.

Deep Dive into Caching for Distributed Systems

· 8 min read

Effective caching can significantly improve the performance and scalability of distributed systems by reducing the load on databases and backend services. This document covers high-level architecture, detailed design, and sample code for implementing caching in distributed systems.

1. Overview and High-Level Architecture​

Caching in distributed systems improves data retrieval speeds, reduces network latency, and offloads backend databases. A typical caching architecture includes clients, a caching layer, and a backend data source. The caching layer can reside in-memory on the application server or be a distributed cache like Redis, Memcached, or Hazelcast.

High-Level Architecture Diagram​

+----------+ +--------------+ +--------------------+
| Clients | <----> | Cache Layer | <----> | Backend Data Store |
+----------+ +--------------+ +--------------------+

Components:

  • Clients: The applications or services making requests for data.
  • Cache Layer: Responsible for storing frequently accessed data, reducing read times.
  • Backend Data Source: The main data storage, typically a database or another service.

2. Cache Design Patterns​

Caching strategies are essential in defining how data is managed between the cache and the main data store.

2.1 Read-Through Cache​

In a read-through cache, requests for data are directed to the cache. If the data is not in the cache, it retrieves it from the database, caches it, and then serves the data.

Diagram:

+--------------+ +----------+ +--------------+
Request | Application | -----> | Cache | -----> | Database |
+--------------+ +----------+ +--------------+
| |
+-----------------------+
(Data cached after first retrieval)

Code Example:

public class ReadThroughCache {
private Cache cache;
private Database database;

public Data getData(String key) {
Data data = cache.get(key);
if (data == null) {
data = database.get(key);
cache.put(key, data);
}
return data;
}
}

2.2 Write-Through Cache​

In this pattern, data is written to the cache and database simultaneously, ensuring cache consistency with the data source.

Diagram:

+--------------+ +----------+ +--------------+
Update | Application | -----> | Cache | -----> | Database |
+--------------+ +----------+ +--------------+
(Writes to cache and database together)

Code Example:

public class WriteThroughCache {
private Cache cache;
private Database database;

public void putData(String key, Data data) {
cache.put(key, data);
database.put(key, data);
}
}

2.3 Write-Behind Cache​

The write-behind cache writes data asynchronously to the backend, which enhances write performance but requires a queue to manage pending updates.

Diagram:

+--------------+ +----------+ +--------------+
Update | Application | -----> | Cache | -----> | Queue |
+--------------+ +----------+ +--------------+
(Data asynchronously written to Database)

Code Example:

import java.util.concurrent.*;

public class WriteBehindCacheService {
private final Cache cache;
private final Database database;
private final ExecutorService executorService;

public WriteBehindCacheService(Cache cache, Database database) {
this.cache = cache;
this.database = database;
this.executorService = Executors.newFixedThreadPool(2);
}

public void putData(String key, Data data) {
// Step 1: Write to cache
cache.put(key, data);

// Step 2: Asynchronously update the database
executorService.submit(() -> database.put(key, data));
}

public Data getData(String key) {
return cache.get(key); // Read from cache
}

public void shutdown() {
executorService.shutdown();
}
}

In this example, when putData is called, the data is immediately written to the cache, and an asynchronous task is created to update the database. This method improves application performance by deferring the database write.

2.4 Cache-Aside Pattern​

With the cache-aside pattern, the application retrieves data directly from the cache. On a cache miss, it loads data from the main store, updates the cache, and returns the result.

Diagram:

+--------------+ +----------+ +--------------+
| Application | ----> | Cache | ----> | Database |
+--------------+ +----------+ +--------------+
| |
(Data fetched and cached when not found in cache)

Code Example:

public class CacheAsideService {
private final Cache cache;
private final Database database;

public CacheAsideService(Cache cache, Database database) {
this.cache = cache;
this.database = database;
}

public Data getData(String key) {
// Step 1: Check cache first
Data data = cache.get(key);

if (data == null) {
// Step 2: Load from database on cache miss
data = database.get(key);

if (data != null) {
// Step 3: Store data in cache for future requests
cache.put(key, data);
}
}
return data;
}

public void putData(String key, Data data) {
// Step 1: Write to database
database.put(key, data);

// Step 2: Invalidate cache or update cache
cache.put(key, data);
}
}

In this example:

  • Read: getData() first tries to read from the cache. If there’s a cache miss, it fetches from the database, adds it to the cache, and returns the data.
  • Write: putData() writes to the database first, then updates or invalidates the cache.

2.5 Differences between Read-Through and Cache-Aside Patterns​

  1. Read-Through Pattern:

    • The cache sits directly in front of the database, intercepting reads.
    • If data is requested, the cache checks if it's present. If it’s a cache miss, it automatically fetches from the database, caches it, and returns the result.
    • This pattern works well for applications where you want to decouple the application logic from the cache management.
    • Common in systems where caching is managed as a service, like using a caching proxy or middleware.
  2. Cache-Aside Pattern:

    • The application controls cache management explicitly.
    • On a read operation, the application first checks the cache. If the data is not present (cache miss), the application fetches it from the database, then stores it in the cache for future use.
    • This pattern gives the application full control over what data is cached, which can optimize cache usage for applications with varying data access patterns.
    • Common in scenarios where cache storage is limited or there’s a need to frequently update specific items based on application logic.
FeatureRead-Through PatternCache-Aside Pattern
Cache ManagementManaged by the cache itselfManaged by the application
Caching BehaviorAutomatically loads from DB on cache missApplication decides when to cache
Best Use CasesFor systems requiring a cache as a serviceFor applications needing custom control over caching
ComplexityLower, as caching logic is handled internallyHigher, as caching must be managed in the application

3. Cache Topologies​

3.1 Single Node Cache​

Single-node caches store data locally on one machine and are simple to manage but lack scalability and resilience.

3.2 Distributed Cache​

A distributed cache spreads data across multiple nodes for scalability, enabling data to be accessed from various locations in a distributed system.

Diagram:

+----------+ +-------------+ +-------------+ +-------------+
| Client 1 |<--->| Cache Node 1|<--->| Cache Node 2|<--->| Cache Node 3|
+----------+ +-------------+ +-------------+ +-------------+

3.3 Hierarchical Cache​

Hierarchical caches use a layered approach to caching, with data stored at different levels depending on usage frequency.

Diagram:

+-------------+
| L1 Cache |
+-------------+
|
+-------------+
| L2 Cache |
+-------------+
|
+-------------+
| Backend DB |
+-------------+

4. Detailed Design and Components​

4.1 Cache Consistency​

Consistency in caching ensures that the data in the cache matches the data in the database. Techniques like cache synchronization and write-through strategies help maintain this consistency.

4.2 Cache Invalidation Strategies​

Cache invalidation ensures that stale data is removed or updated within the cache. Common strategies include:

  • Time-based Expiration: Setting a TTL (Time to Live) for cache entries.
  • Event-based Invalidation: Using events to invalidate cache entries based on specific triggers.

4.3 Eviction Policies​

Eviction policies determine how cache space is managed. Common policies include:

  • Least Recently Used (LRU): Removes data that hasn’t been accessed recently.
  • Least Frequently Used (LFU): Removes data that is accessed least frequently.

5. Implementation​

5.1 Cache Layer Implementation​

Using Redis as an example of a distributed cache layer:

import redis.clients.jedis.Jedis;

public class RedisCacheService {
private Jedis jedis = new Jedis("localhost");

public void put(String key, String value) {
jedis.set(key, value);
}

public String get(String key) {
return jedis.get(key);
}

public void delete(String key) {
jedis.del(key);
}
}

5.2 Cache Invalidation Mechanisms​

Implementing cache invalidation using a TTL and a cache purge mechanism:

import java.util.concurrent.TimeUnit;

public class CacheService {
private Cache cache = new Cache();

public void put(String key, Data value, long ttl, TimeUnit unit) {
cache.put(key, value);
cache.expire(key, ttl, unit);
}
}

6. Monitoring and Metrics​

Monitoring the cache layer provides insights into performance. Using tools like Prometheus and Grafana with metrics for cache hit/miss rates, latency, and eviction rates is essential.

# Example Prometheus configuration for Redis
scrape_configs:
- job_name: 'redis'
static_configs:
- targets: ['localhost:6379']

7. Conclusion​

Distributed caching is a vital component of scalable systems. By understanding different patterns, topologies, and consistency mechanisms, developers can effectively improve system performance and reliability.

Deep Dive into Caffeine Cache and Integration with Spring Boot

· 13 min read

Introduction​

Caffeine is a high-performance, near-optimal caching library for Java, widely used in Spring Boot applications to improve performance by reducing the load on databases and other backend services. This article delves into the details of Caffeine cache, its integration with Spring Boot, and how it works under the hood. We'll also provide real-life production use cases and sample code to illustrate its usage.


Caffeine Cache Overview​

Caffeine is designed to be efficient and easy to use, providing advanced features like eviction policies, time-based expiration, and statistics recording. It uses a combination of data structures and algorithms to manage cache entries efficiently.

Key Features​

  • High Performance: Optimized for fast read and write operations.
  • Eviction Policies: Supports LRU, FIFO, and LFU eviction policies.
  • Time-Based Expiration: Entries can be expired after a specified period of inactivity or since they were last written.
  • Statistics Recording: Tracks cache hits, misses, and evictions for monitoring and tuning.

Configuring Caffeine Cache in Spring Boot​

Adding Dependencies​

First, ensure you have the necessary dependencies in your pom.xml:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>

Enabling Caching​

Enable caching in your Spring Boot application by adding the @EnableCaching annotation to your main application class:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

Configuring Cache Manager​

Create a configuration class to set up Caffeine cache:

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CacheConfig {

@Bean
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager("userCache", "productCache");
cacheManager.setCaffeine(caffeineCacheBuilder());
return cacheManager;
}

Caffeine<Object, Object> caffeineCacheBuilder() {
return Caffeine.newBuilder()
.maximumSize(500)
.expireAfterAccess(600, TimeUnit.SECONDS)
.recordStats();
}
}

YAML Configuration​

You can also configure Caffeine cache using YAML:

spring:
cache:
type: caffeine
cache-names:
- userCache
- productCache
caffeine:
spec: maximumSize=500,expireAfterAccess=600s

Explanation of Caffeine Cache Configuration​

  • CaffeineCacheManager: Manages multiple caches, each identified by a name.
  • Cache Names: "userCache" and "productCache" are used to identify different caches.
  • maximumSize(500): Sets the maximum number of entries the cache can hold.
  • expireAfterAccess(600, TimeUnit.SECONDS): Specifies that entries should be expired after 600 seconds of inactivity.
  • recordStats(): Enables statistics recording for monitoring cache performance.

How Caffeine Cache Works​

Cache Population​

When a cache miss occurs, Caffeine fetches the data from the underlying data source (e.g., database) and stores it in the cache.

Cache Eviction​

Caffeine uses various eviction policies to manage the cache size:

  • Least Recently Used (LRU): Evicts the least recently used entries first.
  • First In, First Out (FIFO): Evicts the oldest entries first.
  • Least Frequently Used (LFU): Evicts the least frequently used entries first.

Expiration​

Caffeine supports time-based expiration:

  • Expire After Access: Entries are expired after a specified period of inactivity.
  • Expire After Write: Entries are expired after a specified period since they were last written.

Statistics​

Caffeine can record statistics such as cache hits, misses, and evictions, which can be useful for monitoring and tuning the cache.

Statistics Recording​

Caffeine provides a recordStats() method that enables the collection of cache statistics. This method returns a Caffeine instance that will record statistics for the cache.

Caffeine<Object, Object> caffeineCacheBuilder() {
return Caffeine.newBuilder()
.maximumSize(500)
.expireAfterAccess(600, TimeUnit.SECONDS)
.recordStats();
}

Tracking Cache Hits, Misses, and Evictions​

Once statistics recording is enabled, you can access the statistics using the stats() method on the cache. This method returns a CacheStats object that contains various metrics:

  • hitCount(): The number of successful cache hits.
  • missCount(): The number of cache misses.
  • evictionCount(): The number of cache evictions.
  • loadSuccessCount(): The number of times a cache miss was successfully loaded.
  • loadFailureCount(): The number of times a cache miss failed to load.

Here's an example of how to access and log cache statistics:

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.stats.CacheStats;

public class CacheStatisticsExample {

public static void main(String[] args) {
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(100)
.recordStats()
.build();

// Perform cache operations
cache.put("key1", "value1");
cache.getIfPresent("key1");
cache.getIfPresent("key2");

// Access cache statistics
CacheStats stats = cache.stats();
System.out.println("Cache Hits: " + stats.hitCount());
System.out.println("Cache Misses: " + stats.missCount());
System.out.println("Cache Evictions: " + stats.evictionCount());
}
}

Caffeine Cache Internals​

Cache Interface​

The Cache interface defines the core operations for interacting with the cache:

public interface Cache<K, V> {
V getIfPresent(K key);
V get(K key, Function<? super K, ? extends V> mappingFunction);
void put(K key, V value);
void invalidate(K key);
void invalidateAll();
long estimatedSize();
CacheStats stats();
}

Caffeine Class​

The Caffeine class is the builder for creating cache instances:

public final class Caffeine<K, V> {
public static <K, V> Caffeine<K, V>newBuilder() {
return new Caffeine<>();
}

public Caffeine<K, V> maximumSize(long maximumSize) {
// Implementation
return this;
}

public Caffeine<K, V> expireAfterAccess(long duration, TimeUnit unit) {
// Implementation
return this;
}

public Cache<K, V> build() {
// Implementation
return new BoundedLocalCache<>(this);
}
}

BoundedLocalCache Class​

The BoundedLocalCache class is the core implementation of the cache, handling operations like get, put, and eviction:

final class BoundedLocalCache<K, V> extends LocalCache<K, V> {
BoundedLocalCache(Caffeine<K, V> builder) {
// Initialization
}

@Override
public V getIfPresent(Object key) {
// Implementation
}

@Override
public void put(K key, V value) {
// Implementation
}

@Override
public void invalidate(Object key) {
// Implementation
}

@Override
public long estimatedSize() {
// Implementation
}

@Override
public CacheStats stats() {
// Implementation
}
}

Detailed Logic in Caffeine Cache​

Cache Lookup​

Caffeine uses a ConcurrentHashMap to store cache entries. When a lookup is performed, Caffeine checks if the key exists in the map:

public V getIfPresent(Object key) {
Node<K, V> node = data.get(key);
if (node == null) {
return null;
}
// Additional logic for expiration and eviction checks
return node.getValue();
}

Cache Miss and Method Execution​

If the key is not found in the cache, the method is executed, and the result is stored in the cache:

public V get(K key, Function<? super K, ? extends V> mappingFunction) {
V value = getIfPresent(key);
if (value != null) {
return value;
}
value = mappingFunction.apply(key);
put(key, value);
return value;
}

Cache Update​

When the result is fetched from the database, it is stored in the cache:

public void put(K key, V value) {
Node<K, V> node = new Node<>(key, value);
data.put(key, node);
// Additional logic for eviction and expiration
}

Real-Life Production Use Cases​

1. User Profile Caching​

In a social media application, user profiles are frequently accessed. Caching user profiles can significantly reduce the load on the database and improve response times.

2. Product Catalog Caching​

In an e-commerce application, product catalogs are often large and frequently accessed. Caching product data can improve performance and reduce database load.

3. API Response Caching​

In microservices, caching API responses can reduce the number of calls to downstream services, improving overall system performance.

4. Session Data Caching​

In applications with user sessions, caching session data can reduce the load on session storage systems and improve scalability.


Sample Code​

Caffeine Cache Configuration​

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CacheConfig {

@Bean
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager("userCache", "productCache");
cacheManager.setCaffeine(caffeineCacheBuilder());
return cacheManager;
}

Caffeine<Object, Object> caffeineCacheBuilder() {
return Caffeine.newBuilder()
.maximumSize(500)
.expireAfterAccess(600, TimeUnit.SECONDS)
.recordStats();
}
}

User Service with Caching​

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

@Cacheable(value = "userCache", key = "#userId")
public User getUserById(Long userId) {
// Fetch user from database
return fetchUserFromDatabase(userId);
}

private User fetchUserFromDatabase(Long userId) {
// Database query logic
return new User(userId, "John Doe");
}
}

Flow Diagram​

Here's a textual diagram to illustrate the flow:

graph TD
A[Client Request] --> B{Cache Lookup}
B -->|Cache Hit| C[Return Cached Data]
B -->|Cache Miss| D[Execute Method]
D --> E[Fetch from Database]
E --> F[Update Cache]
F --> C

Explanation of the Flow Diagram​

  1. Client Request: The client makes a request to fetch a user by ID.
  2. Cache Lookup: The cache manager looks up the userId in the "userCache".
  3. Cache Hit: If the user is found in the cache, the cached data is returned immediately.
  4. Cache Miss: If the user is not found in the cache, the method getUserById(Long userId) is executed.
  5. Execute Method: The method fetches the user from the database.
  6. Fetch from Database: The user is retrieved from the database.
  7. Update Cache: The fetched user is stored in the cache.
  8. Return Cached Data: The user data is returned to the client.

Statistics Logging, Tracking and Mornitoring​

Caffeine's statistics can be tracked using logging tools and even integrated with GUI tools for better visualization and monitoring.

1. Logging Cache Statistics​

Log cache statistics using a logging framework like SLF4J or Log4j. This allows you to periodically log the cache metrics to a log file or console.

Example: Logging Cache Statistics with SLF4J​

First, add the necessary dependencies in pom.xml:

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.32</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.32</version>
</dependency>

Next, configure cache to log statistics periodically:

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class CacheStatisticsLogger {

private static final Logger logger = LoggerFactory.getLogger(CacheStatisticsLogger.class);

public static void main(String[] args) {
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(100)
.recordStats()
.build();

// Perform cache operations
cache.put("key1", "value1");
cache.getIfPresent("key1");
cache.getIfPresent("key2");

// Log cache statistics
logCacheStats(cache);
}

private static void logCacheStats(Cache<?, ?> cache) {
CacheStats stats = cache.stats();
logger.info("Cache Hits: {}", stats.hitCount());
logger.info("Cache Misses: {}", stats.missCount());
logger.info("Cache Evictions: {}", stats.evictionCount());
logger.info("Load Success Count: {}", stats.loadSuccessCount());
logger.info("Load Failure Count: {}", stats.loadFailureCount());
}
}

2. Integrating with GUI Tools​

Integrate Caffeine's statistics with GUI tools like Grafana or Prometheus for better visualization and monitoring. Here's an example of how to integrate with Prometheus and Grafana.

Step 1: Add Prometheus and Grafana Dependencies​

Add the necessary dependencies to pom.xml:

<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient</artifactId>
<version>0.15.0</version>
</dependency>
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_hotspot</artifactId>
<version>0.15.0</version>
</dependency>
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_servlet</artifactId>
<version>0.15.0</version>
</dependency>
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_spring_boot</artifactId>
<version>0.15.0</version>
</dependency>

Step 2: Configure Prometheus Metrics Collector​

Create a configuration class to collect cache statistics using Prometheus:

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.Gauge;
import io.prometheus.client.exporter.MetricsServlet;
import io.prometheus.client.hotspot.DefaultExports;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Configuration
public class PrometheusConfig {

private final Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(100)
.recordStats()
.build();

private final Counter cacheHits = Counter.build()
.name("cache_hits_total")
.help("Total number of cache hits.")
.register();

private final Counter cacheMisses = Counter.build()
.name("cache_misses_total")
.help("Total number of cache misses.")
.register();

private final Counter cacheEvictions = Counter.build()
.name("cache_evictions_total")
.help("Total number of cache evictions.")
.register();

private final Gauge cacheSize = Gauge.build()
.name("cache_size")
.help("Current size of the cache.")
.register();

@PostConstruct
public void init() {
DefaultExports.initialize();
}

@Bean
public ServletRegistrationBean<MetricsServlet> metricsServlet() {
CollectorRegistry collectorRegistry = new CollectorRegistry();
collectorRegistry.register(cacheHits);
collectorRegistry.register(cacheMisses);
collectorRegistry.register(cacheEvictions);
collectorRegistry.register(cacheSize);
return new ServletRegistrationBean<>(new MetricsServlet(collectorRegistry), "/metrics");
}

@Bean
public Cache<String, String> cache() {
return cache;
}

@Bean
public Runnable cacheStatsCollector() {
return () -> {
CacheStats stats = cache.stats();
cacheHits.inc(stats.hitCount());
cacheMisses.inc(stats.missCount());
cacheEvictions.inc(stats.evictionCount());
cacheSize.set(cache.estimatedSize());
};
}
}

Step 3: Configure Prometheus and Grafana​

  1. Prometheus: Configure Prometheus to scrape the metrics endpoint (/metrics) of the Spring Boot application.

  2. Grafana: Set up Grafana to visualize the metrics collected by Prometheus. Dashboards can be created to display cache hits, misses, evictions, and other relevant metrics.

Example: Prometheus Configuration​

Create a prometheus.yml file:

global:
scrape_interval: 15s

scrape_configs:
- job_name: 'spring-boot-app'
metrics_path: '/metrics'
static_configs:
- targets: ['localhost:8080']

Example: Grafana Dashboard​

  1. Add Prometheus as a Data Source in Grafana.
  2. Create a Dashboard and add panels to visualize the cache metrics:
    • Cache Hits: cache_hits_total
    • Cache Misses: cache_misses_total
    • Cache Evictions: cache_evictions_total
    • Cache Size: cache_size

Summary​

By logging cache statistics using a logging framework like SLF4J or integrating with monitoring tools like Prometheus and Grafana, we can effectively track and visualize the performance of the Caffeine cache. This allows us to monitor cache hits, misses, evictions, and other metrics, helping us to tune and optimize the cache for better performance.

Conclusion​

Caffeine cache is a powerful tool for improving the performance and scalability of Spring Boot applications. By understanding how Caffeine works, including its eviction policies and expiration

Deep Dive into Finding Numbers in Strings with Python

· 6 min read

Introduction​

Handling strings that contain a mix of numbers and text is a common task in everyday programming. For example, you might need to extract numbers from complex text or identify whether certain strings contain numbers. In Python, there are various ways to tackle this problem, depending on your specific needs. This article will detail how to find numbers in strings using Python, providing concrete example code to help developers quickly master these techniques.


Why Find Numbers in Strings?​

  • Data Processing and Cleaning: Extract useful numeric information from web crawlers or log files, such as order numbers, timestamps, amounts, etc.
  • Input Validation: Detect whether user input strings contain numbers to ensure the validity of the input content.
  • Text Analysis: Extract numbers from text data for further data analysis or statistics.

Using String's isnumeric() Method​

Python's string type (str) provides several methods to determine character types, one of which is isnumeric(). The isnumeric() method checks whether a string contains only numeric characters. If all characters in the string are numeric, the method returns True; otherwise, it returns False.

string = "12345"
if string.isnumeric():
print(f"'{string}' contains only numbers")
else:
print(f"'{string}' contains more than just numbers")

In this example, isnumeric() checks if the string "12345" consists entirely of numeric characters. Although this method can determine if a string is entirely numeric, it cannot extract numbers from mixed strings.


Using Regular Expressions to Find Numbers​

Regular expressions (regex) are a powerful tool for text processing, ideal for finding and extracting numbers from strings. Python's re module provides comprehensive regex support, making it easy to match numbers in strings.

Example: Using Regular Expressions​

import re

# Define a string containing numbers
text = "Order number is 12345, amount is 678.90 dollar"

# Use regex to find all numbers
numbers = re.findall(r'\d+', text)

print(f"Numbers found in the string: {numbers}")

In this example, re.findall() uses the regex \d+, which matches one or more consecutive digits. re.findall() returns a list containing all matched numbers in the string. The output is: ['12345', '678'].


Finding Numbers with Decimal Points​

If you need to find numbers with decimal points in a string, you can use the following regex:

import re

text = "Order number is 12345, amount is 678.90 dollar"

# Find integers and decimals
numbers = re.findall(r'\d+\.?\d*', text)

print(f"Numbers found in the string: {numbers}")

In this regex, \d+ matches one or more digits, \. matches the decimal point, and \d* matches zero or more digits following the decimal point. The result is: ['12345', '678.90'].


Using List Comprehension to Extract Numbers​

For simple scenarios, you can use Python's list comprehension to quickly extract numbers from a string. By checking each character in the string to see if it is a digit, you can extract them.

Example: Using List Comprehension​

text = "Order number 12345, amount 678.90 dollar"

# Extract digit characters
digits = [char for char in text if char.isdigit()]

print(f"Extracted digit characters: {digits}")

In this example, isdigit() is used to check each character in the string, resulting in a list of all digit characters: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']. If you need to combine the extracted digits into a complete numeric string, you can use the join() method:

# Combine extracted digit characters into a complete numeric string
number_str = ''.join(digits)
print(f"Complete numeric string: {number_str}")

The output is: "1234567890".


Filtering Numbers with filter() Function​

Python's built-in filter() function can be used to filter out non-numeric characters from a string, thereby extracting numeric characters. The filter() function works similarly to list comprehension but is more functional in style.

Example: Using filter() Function​

text = "Order number 12345, amount 678.90 dollar"

# Use the filter function to extract numbers
numbers = ''.join(filter(str.isdigit, text))

print(f"Extracted numbers: {numbers}")

In this example, the filter() function checks each character in the string, keeping only those that satisfy isdigit(), and then joins the extracted numeric characters into a complete string.


Splitting Strings to Extract Numbers​

In some scenarios, you can split the string first and then process each segment to extract numbers. The split() method can split a string into multiple parts based on a specified delimiter, suitable for handling structured text.

Example: Using split() Method​

import re

text = "Order number: 12345, amount: 678.90"

# Split the string by spaces or punctuation
parts = re.split(r'[,:: ]+', text)

# Extract numeric parts
numbers = [part for part in parts if part.replace('.', '', 1).isdigit()]

print(f"Extracted numbers: {numbers}")

In this example, re.split() is used to split the string, and then list comprehension extracts all numeric parts. replace('.', '', 1) ensures that decimal points are handled correctly.


Using ast.literal_eval to Parse Numbers​

In some applications, you may need to extract numeric values from complex strings and parse them into numeric types (integers or floats). Python's ast.literal_eval() method can safely parse a string into a Python data type.

Example: Using ast.literal_eval​

import ast
import re

text = "Amount: 678.90"

# Extract the numeric part of the string
number_str = re.search(r'\d+\.?\d*', text).group()

# Parse the string into a number
number = ast.literal_eval(number_str)

print(f"Parsed number: {number}")

In this example, the regex extracts the numeric part, and ast.literal_eval() converts it into the actual numeric type (float). This method is useful for extracting and converting numbers from text.


Conclusion​

Finding and extracting numbers from strings is a common task in Python programming, whether for data cleaning, user input validation, or text analysis. This article has introduced various methods to find numbers in Python, including using string methods, regular expressions, list comprehension, the filter() function, and ast.literal_eval(). Each method has its strengths and can be chosen based on different application scenarios. With these tools, developers can quickly and efficiently extract and process numeric data from strings, enhancing code flexibility and processing capabilities.

Deep Dive into Keycloak

· 5 min read

Introduction​

Keycloak is an open-source Identity and Access Management (IAM) solution that provides authentication, authorization, and user management for modern applications and services. It is designed to be easy to integrate with existing systems and supports a wide range of protocols and standards, including OAuth 2.0, OpenID Connect, and SAML. This article will delve into the architecture of Keycloak, exploring its components, features, and practical applications.

Keycloak Architecture​

2.1 Overview​

Keycloak is built on a modular architecture that allows for flexibility and extensibility. It consists of several key components that work together to provide a comprehensive IAM solution. The architecture can be divided into the following main areas:

  • Authentication: Handles user authentication and session management.
  • Authorization: Provides fine-grained access control and permissions management.
  • User Federation: Integrates with external user stores.
  • Identity Brokering: Allows users to authenticate using external identity providers.
  • Admin Console: Provides a web-based interface for managing Keycloak.

2.2 Key Components​

+-------------------+ +-------------------+ +-------------------+
| Client Application| | Keycloak Server | | External Identity |
| (e.g., Web App) | | (Auth Server) | | Provider (e.g., |
| | | | | Google, Facebook)|
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Authentication Request| |
|-------------------------->| |
| | (2) Redirect to Auth Server|
| |-------------------------->|
| | |
| | (3) User Authentication |
| |<--------------------------|
| | |
| | (4) Authorization Grant |
| |<--------------------------|
| | |
| | (5) Access Token Request |
| |-------------------------->|
| | |
| | (6) Access Token Response|
| |<--------------------------|
| | |
| (7) Access Resource | |
|<--------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| Resource Server | | Keycloak Server | | External Identity |
| (e.g., API) | | (Auth Server) | | Provider (e.g., |
| | | | | Google, Facebook)|
+-------------------+ +-------------------+ +-------------------+

2.3 Authentication Flows​

Keycloak supports various authentication flows, including:

  • Standard Flow: The default flow where the client redirects the user to the Keycloak server for authentication.
  • Implicit Flow: Suitable for client-side applications where the access token is returned directly to the client.
  • Direct Access Grants: Allows clients to obtain an access token using the resource owner's credentials.
  • Client Credentials: Used for machine-to-machine communication.

2.4 Authorization Services​

Keycloak provides fine-grained authorization services, including:

  • Role-Based Access Control (RBAC): Assigns roles to users and defines permissions based on those roles.
  • Policy-Based Access Control (PBAC): Uses policies to define complex access control rules.
  • Permission Management: Allows administrators to manage permissions for resources and users.

2.5 User Federation​

Keycloak supports user federation, allowing integration with external user stores such as LDAP and Active Directory. This enables organizations to manage users in their existing user stores while leveraging Keycloak for authentication and authorization.

2.6 Identity Brokering​

Keycloak supports identity brokering, allowing users to authenticate using external identity providers such as Google, Facebook, and GitHub. This enables organizations to provide a seamless authentication experience for users who prefer to use their existing accounts.

2.7 Admin Console​

Keycloak provides a web-based admin console that allows administrators to manage users, roles, clients, and other Keycloak entities. The admin console is a powerful tool for configuring and managing Keycloak.

Practical Applications​

3.1 Single Sign-On (SSO)​

Keycloak enables Single Sign-On (SSO), allowing users to authenticate once and access multiple applications without re-entering their credentials. This is particularly useful in enterprise environments where users need to access multiple internal applications.

3.2 API Security​

Keycloak is widely used to secure APIs by providing access tokens that grant limited access to resources. This is essential for building secure microservices architectures.

3.3 User Management​

Keycloak provides comprehensive user management features, including user registration, profile management, and password management. It also supports user federation, allowing integration with external user stores.

3.4 Custom Extensions​

Keycloak is highly extensible, allowing developers to create custom extensions to meet specific requirements. This includes custom authentication flows, custom user federation providers, and custom identity providers.

Conclusion​

Keycloak is a powerful and flexible Identity and Access Management solution that provides comprehensive authentication, authorization, and user management capabilities. Its modular architecture and support for various protocols and standards make it a popular choice for securing modern applications and services.

Understanding the architecture and features of Keycloak is essential for developers and administrators who want to leverage its capabilities to build secure and scalable applications. By leveraging Keycloak, organizations can provide a seamless and secure authentication and authorization experience for their users.

References​


This article provides a comprehensive overview of Keycloak, covering its architecture, components, and practical applications. By understanding Keycloak, developers and administrators can build secure and scalable applications that meet the demands of today's digital landscape.

Deep Dive into MapStruct: A Java Bean Mapping Framework

· 6 min read
  1. Introduction
  2. Why Use MapStruct?
  3. How to Use MapStruct in Spring Boot
  4. Benefits and Advantages
  5. Textual Diagram
  6. Sample Code
  7. Generated Mapper Code
  8. Excluding Certain Attributes
  9. Conclusion

Introduction​

MapStruct is a Java annotation processor for the generation of type-safe and performant bean mapping code. It simplifies the mapping between different Java bean types by automatically generating the necessary mapping code at compile time. This article will explore why and how to use MapStruct in a Spring Boot application, its benefits and advantages, and provide detailed sample code.


Why Use MapStruct?​

Manual Mapping​

Manual mapping between Java beans can be tedious and error-prone. It often involves writing repetitive and boilerplate code, which can lead to maintenance issues.

Reflection-Based Mapping​

Frameworks like Dozer use reflection to map beans, which can be slow and difficult to debug. Reflection-based mapping also lacks type safety and can lead to runtime errors.

MapStruct​

MapStruct generates mapping code at compile time, ensuring type safety and performance. It reduces boilerplate code and makes the mapping process more maintainable and easier to debug.


How to Use MapStruct in Spring Boot​

Step 1: Add Dependencies​

Add the necessary dependencies to your pom.xml file. Note that we are using the latest version of MapStruct.

<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<!-- MapStruct -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.3.Final</version>
</dependency>

<!-- MapStruct Processor -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.3.Final</version>
<scope>provided</scope>
</dependency>
</dependencies>

Step 2: Define Mapping Interface​

Create a mapping interface using the @Mapper annotation.

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Mapper
public interface UserMapper {
UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);

@Mapping(source = "emailAddress", target = "email")
@Mapping(source = "birthDate", target = "birthDate", dateFormat = "yyyyMMdd")
@Mapping(target = "password", ignore = true) // Exclude password attribute
UserDTO userToUserDTO(User user);

@Mapping(source = "email", target = "emailAddress")
@Mapping(target = "birthDate", expression = "java(LocalDate.parse(userDTO.getBirthDate(), DateTimeFormatter.ofPattern(\"yyyyMMdd\")))")
@Mapping(target = "password", ignore = true) // Exclude password attribute
User userDTOToUser(UserDTO userDTO);
}

Step 3: Use the Mapper​

Inject the mapper into your service or controller and use it to map between beans.

import org.springframework.stereotype.Service;

@Service
public class UserService {
private final UserMapper userMapper = UserMapper.INSTANCE;

public UserDTO getUserDTO(User user) {
return userMapper.userToUserDTO(user);
}

public User getUser(UserDTO userDTO) {
return userMapper.userDTOToUser(userDTO);
}
}

Benefits and Advantages​

Type Safety​

MapStruct generates type-safe mapping code at compile time, reducing the risk of runtime errors.

Performance​

Since the mapping code is generated at compile time, it avoids the performance overhead associated with reflection-based mapping.

Maintainability​

MapStruct reduces boilerplate code, making the mapping process more maintainable and easier to understand.

Customization​

MapStruct allows for easy customization of mappings through annotations and configuration options.


Textual Diagram​

graph TD
A[User Entity] -->|MapStruct| B[User DTO]
B -->|MapStruct| C[User Entity]
D[User Service] -->|Uses| A
D -->|Uses| B
E[User Controller] -->|Uses| D

Explanation​

  1. User Entity: Represents the domain object.
  2. User DTO: Represents the data transfer object.
  3. MapStruct: Generates mapping code between User Entity and User DTO.
  4. User Service: Uses the MapStruct-generated mapper to convert between User Entity and User DTO.
  5. User Controller: Uses the User Service to handle requests and responses.

Sample Code​

User Entity​

import java.time.LocalDate;

public class User {
private Long id;
private String name;
private String emailAddress;
private LocalDate birthDate;
private String password; // Password attribute to be excluded

// Getters and Setters
}

User DTO​

public class UserDTO {
private Long id;
private String name;
private String email;
private String birthDate;
private String password; // Password attribute to be excluded

// Getters and Setters
}

User Mapper​

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Mapper
public interface UserMapper {
UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);

@Mapping(source = "emailAddress", target = "email")
@Mapping(source = "birthDate", target = "birthDate", dateFormat = "yyyyMMdd")
@Mapping(target = "password", ignore = true) // Exclude password attribute
UserDTO userToUserDTO(User user);

@Mapping(source = "email", target = "emailAddress")
@Mapping(target = "birthDate", expression = "java(LocalDate.parse(userDTO.getBirthDate(), DateTimeFormatter.ofPattern(\"yyyyMMdd\")))")
@Mapping(target = "password", ignore = true) // Exclude password attribute
User userDTOToUser(UserDTO userDTO);
}

User Service​

import org.springframework.stereotype.Service;

@Service
public class UserService {
private final UserMapper userMapper = UserMapper.INSTANCE;

public UserDTO getUserDTO(User user) {
return userMapper.userToUserDTO(user);
}

public User getUser(UserDTO userDTO) {
return userMapper.userDTOToUser(userDTO);
}
}

User Controller​

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;

@GetMapping("/{id}")
public UserDTO getUserDTO(@PathVariable Long id) {
User user = new User(); // Assume this is fetched from a repository
return userService.getUserDTO(user);
}

@PostMapping
public User createUser(@RequestBody UserDTO userDTO) {
return userService.getUser(userDTO);
}
}

Generated Mapper Code​

After compiling the project, MapStruct will generate the following mapper implementation:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class UserMapperImpl implements UserMapper {

@Override
public UserDTO userToUserDTO(User user) {
if (user == null) {
return null;
}

UserDTO userDTO = new UserDTO();
userDTO.setId(user.getId());
userDTO.setName(user.getName());
userDTO.setEmail(user.getEmailAddress());
userDTO.setBirthDate(user.getBirthDate().format(DateTimeFormatter.ofPattern("yyyyMMdd")));

return userDTO;
}

@Override
public User userDTOToUser(UserDTO userDTO) {
if (userDTO == null) {
return null;
}

User user = new User();
user.setId(userDTO.getId());
user.setName(userDTO.getName());
user.setEmailAddress(userDTO.getEmail());
user.setBirthDate(LocalDate.parse(userDTO.getBirthDate(), DateTimeFormatter.ofPattern("yyyyMMdd")));

return user;
}
}

Excluding Certain Attributes​

Exclude Attribute Example​

In the UserMapper interface, we use the @Mapping annotation with ignore = true to exclude the password attribute from the mapping.

@Mapper
public interface UserMapper {
UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);

@Mapping(source = "emailAddress", target = "email")
@Mapping(source = "birthDate", target = "birthDate", dateFormat = "yyyyMMdd")
@Mapping(target = "password", ignore = true) // Exclude password attribute
UserDTO userToUserDTO(User user);

@Mapping(source = "email", target = "emailAddress")
@Mapping(target = "birthDate", expression = "java(LocalDate.parse(userDTO.getBirthDate(), DateTimeFormatter.ofPattern(\"yyyyMMdd\")))")
@Mapping(target = "password", ignore = true) // Exclude password attribute
User userDTOToUser(UserDTO userDTO);
}

Generated Mapper Code with Exclusion​

The generated mapper code will exclude the password attribute from the mapping.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class UserMapperImpl implements UserMapper {

@Override
public UserDTO userToUserDTO(User user) {
if (user == null) {
return null;
}

UserDTO userDTO = new UserDTO();
userDTO.setId(user.getId());
userDTO.setName(user.getName());
userDTO.setEmail(user.getEmailAddress());
userDTO.setBirthDate(user.getBirthDate().format(DateTimeFormatter.ofPattern("yyyyMMdd")));

return userDTO;
}

@Override
public User userDTOToUser(UserDTO userDTO) {
if (userDTO == null) {
return null;
}

User user = new User();
user.setId(userDTO.getId());
user.setName(userDTO.getName());
user.setEmailAddress(userDTO.getEmail());
user.setBirthDate(LocalDate.parse(userDTO.getBirthDate(), DateTimeFormatter.ofPattern("yyyyMMdd")));

return user;
}
}

Conclusion​

MapStruct is a powerful and efficient Java bean mapping framework that simplifies the process of mapping between different Java bean types. By generating type-safe and performant mapping code at compile time, MapStruct reduces boilerplate code, improves maintainability, and enhances the overall quality of your Spring Boot applications. Whether you are working on a small project or a large enterprise application, MapStruct is a valuable tool that can significantly streamline your development process.

Deep Dive into Memory Cache in Spring Boot Application

· 13 min read

Table of Contents​


Introduction​

In modern microservice architectures, performance and scalability are critical. Memory caching is a powerful technique to improve application performance by reducing the load on databases and other backend services. This article delves into the design and implementation of memory caches in Spring Boot applications, focusing on real-life project scenarios and the latest technology stack.


Understanding Memory Cache​

A memory cache is a high-speed data storage layer that stores a subset of data, typically transient in nature, so that future requests for that data are served faster. Caching can significantly improve the performance and scalability of applications by reducing the need to access slower underlying storage layers.

Key Concepts​

  • Cache Hit: When the requested data is found in the cache.
  • Cache Miss: When the requested data is not found in the cache.
  • Cache Eviction: The process of removing data from the cache to make room for new data.

Cache Design Principles​

1. Cache Hit and Miss​

  • Cache Hit: When the requested data is found in the cache.
  • Cache Miss: When the requested data is not found in the cache.

2. Cache Eviction Policies​

  • Least Recently Used (LRU): Removes the least recently used items first.
  • First In, First Out (FIFO): Removes the oldest items first.
  • Least Frequently Used (LFU): Removes the least frequently used items first.

3. Cache Invalidation​

  • Time-to-Live (TTL): Data is automatically invalidated after a certain period.
  • Event-Driven Invalidation: Data is invalidated based on specific events (e.g., data updates).

Cache Implementation in Spring Boot​

Spring Boot Cache Abstraction​

Spring Boot provides a powerful cache abstraction that allows you to apply caching to your methods with minimal configuration. The core annotation is @Cacheable, which caches the result of a method invocation.

Caffeine Cache Integration​

Caffeine is a high-performance, near-optimal caching library for Java. It is widely used in Spring Boot applications due to its efficiency and ease of integration.

Cache Configuration​

To configure Caffeine cache in a Spring Boot application, you need to add the following dependencies:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>

Next, enable caching in your Spring Boot application by adding the @EnableCaching annotation to your main application class:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

YAML Configuration​

You can also configure Caffeine cache using YAML:

spring:
cache:
type: caffeine
cache-names:
- userCache
- productCache
caffeine:
spec: maximumSize=500,expireAfterAccess=600s

Detailed Logic in Caffeine Cache​

When you annotate a method with @Cacheable in Spring Boot, the cache manager will first check if the requested data is already present in the specified cache. If the data is found, it will be returned immediately, bypassing the method's execution. If the data is not found, the method will be executed, and the result will be stored in the cache for future requests.

Cache Lookup​

Caffeine uses a ConcurrentHashMap to store cache entries. When a lookup is performed, Caffeine checks if the key exists in the map:

public V getIfPresent(Object key) {
Node<K, V> node = data.get(key);
if (node == null) {
return null;
}
// Additional logic for expiration and eviction checks
return node.getValue();
}

Cache Miss and Method Execution​

If the key is not found in the cache, the method is executed, and the result is stored in the cache:

public V get(K key, Function<? super K, ? extends V> mappingFunction) {
V value = getIfPresent(key);
if (value != null) {
return value;
}
value = mappingFunction.apply(key);
put(key, value);
return value;
}

Cache Update​

When the result is fetched from the database, it is stored in the cache:

public void put(K key, V value) {
Node<K, V> node = new Node<>(key, value);
data.put(key, node);
// Additional logic for eviction and expiration
}

Microservice Architecture and Cache​

Cache Consistency​

Ensuring cache consistency is crucial in distributed systems. Techniques like cache invalidation, event-driven updates, and distributed locking can be used to maintain consistency.

Cache Eviction Strategies​

Choosing the right eviction strategy is important. LRU is commonly used, but in scenarios with frequent updates, LFU or custom eviction policies might be more appropriate.


Complex Scenario 1: Flow Control and Backpressure Handling​

Problem Statement​

In high-traffic scenarios, the cache might become a bottleneck if not properly managed. Flow control and backpressure handling are essential to prevent the cache from being overwhelmed.

Solution Architecture​

  1. Rate Limiting: Implement rate limiting to control the number of requests hitting the cache.
  2. Circuit Breaker: Use a circuit breaker to handle failures gracefully and prevent cascading failures.
  3. Backpressure Handling: Implement backpressure mechanisms to manage the flow of data between services.

Flow Chart​

graph TD
A[Client Request] --> B{Rate Limiter}
B -->|Allowed| C[Cache Lookup]
B -->|Denied| D[Fallback to Database]
C --> E{Cache Hit?}
E -->|Yes| F[Return Cached Data]
E -->|No| G[Fetch from Database]
G --> H[Update Cache]
H --> F
D --> G

Sample Code​

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

@Cacheable(value = "userCache", key = "#userId")
public User getUserById(Long userId) {
// Fetch user from database
return fetchUserFromDatabase(userId);
}

private User fetchUserFromDatabase(Long userId) {
// Database query logic
return new User();
}
}

Complex Scenario 2: Cache Invalidation and Data Synchronization​

Problem Statement​

Ensuring that the cache remains consistent with the underlying data store is challenging, especially in distributed systems.

Solution Architecture​

  1. Event-Driven Invalidation: Use event-driven mechanisms to invalidate the cache when data changes.
  2. Distributed Locking: Use distributed locking to ensure that only one service updates the cache at a time.
  3. TTL-Based Invalidation: Use Time-to-Live (TTL) to automatically invalidate cache entries after a certain period.

Sequence Diagram​

sequenceDiagram
participant Client
participant Service
participant Cache
participant Database

Client->>Service: Update User
Service->>Database: Update User in Database
Database-->>Service: User Updated
Service->>Cache: Invalidate User Cache
Cache-->>Service: Cache Invalidated
Service-->>Client: User Updated

Sample Code​

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

@Service
public class UserService {

@CacheEvict(value = "userCache", key = "#userId")
public void updateUser(Long userId, User user) {
// Update user in database
updateUserInDatabase(userId, user);
}

private void updateUserInDatabase(Long userId, User user) {
// Database update logic
}
}

Complex Scenario 3: Cache Stampede Prevention​

Problem Statement​

A cache stampede occurs when multiple requests for the same data hit the cache simultaneously, leading to a spike in database load.

Solution Architecture​

  1. Probabilistic Early Expiration: Use probabilistic early expiration to spread out cache expiration times.
  2. Locking Mechanism: Implement a locking mechanism to ensure that only one request populates the cache at a time.
  3. Background Refresh: Use background refresh to keep the cache up-to-date without impacting the user experience.

Flow Chart​

graph TD
A[Client Request] --> B{Cache Hit?}
B -->|Yes| C[Return Cached Data]
B -->|No| D{Lock Acquired?}
D -->|Yes| E[Fetch from Database]
D -->|No| F[Wait for Lock]
E --> G[Update Cache]
G --> C
F --> B

Sample Code​

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class UserService {

private final Lock lock = new ReentrantLock();

@Cacheable(value = "userCache", key = "#userId")
public User getUserById(Long userId) {
try {
lock.lock();
// Double-check to ensure the cache is still empty
User cachedUser = fetchUserFromCache(userId);
if (cachedUser != null) {
return cachedUser;
}
// Fetch user from database
User user = fetchUserFromDatabase(userId);
// Update cache
updateCache(userId, user);
return user;
} finally {
lock.unlock();
}
}

private User fetchUserFromCache(Long userId) {
// Cache lookup logic
return null;
}

private User fetchUserFromDatabase(Long userId) {
// Database query logic
return new User();
}

private void updateCache(Long userId, User user) {
// Cache update logic
}
}

Real-Life Production Use Cases​

1. User Profile Caching​

In a social media application, user profiles are frequently accessed. Caching user profiles can significantly reduce the load on the database and improve response times.

2. Product Catalog Caching​

In an e-commerce application, product catalogs are often large and frequently accessed. Caching product data can improve performance and reduce database load.

3. API Response Caching​

In microservices, caching API responses can reduce the number of calls to downstream services, improving overall system performance.

4. Session Data Caching​

In applications with user sessions, caching session data can reduce the load on session storage systems and improve scalability.


Sample Code​

Caffeine Cache Configuration​

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class CacheConfig {

@Bean
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager("userCache", "productCache");
cacheManager.setCaffeine(caffeineCacheBuilder());
return cacheManager;
}

Caffeine<Object, Object> caffeineCacheBuilder() {
return Caffeine.newBuilder()
.maximumSize(500)
.expireAfterAccess(600, TimeUnit.SECONDS);
}
}

User Service with Caching​

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

@Cacheable(value = "userCache", key = "#userId")
public User getUserById(Long userId) {
// Fetch user from database
return fetchUserFromDatabase(userId);
}

private User fetchUserFromDatabase(Long userId) {
// Database query logic
return new User();
}
}

Rate Limiting for Cache Access​

Why Rate Limiting is Needed​

Reading from a memory cache is generally very fast and should not be a bottleneck in terms of performance. However, there are several reasons why you might still want to implement rate limiting for cache access, even if the cache is in memory:

  1. Resource Management: Even though reading from memory is fast, excessive concurrent requests can still consume a significant amount of CPU and memory resources. Rate limiting helps manage these resources more effectively, ensuring that the system remains responsive and does not become overwhelmed.

  2. Preventing Cache Stampede: While reading from the cache is fast, if the cache is not populated (cache miss), all concurrent requests will end up fetching the data from the database or another slow data source. This can lead to a cache stampede, where the database or other backend services are overwhelmed with requests. Rate limiting can help mitigate this by controlling the number of concurrent requests that can hit the cache.

  3. Graceful Degradation: In high-traffic scenarios, rate limiting ensures that the system can gracefully degrade its performance. By limiting the number of requests that can access the cache, you can prevent the system from becoming unresponsive or crashing under heavy load.

  4. Security and Denial of Service (DoS) Prevention: Rate limiting can also be a security measure to prevent Denial of Service (DoS) attacks. By limiting the number of requests from a single client or IP address, you can protect the system from being overwhelmed by malicious requests.

  5. Ensuring Fairness: Rate limiting ensures that all clients have fair access to the cache. Without rate limiting, a few clients with high request rates could monopolize the cache, leading to poor performance for other clients.

  6. Monitoring and Analytics: Rate limiting provides valuable data on the usage patterns of the cache. This data can be used for monitoring, analytics, and capacity planning.

Example: Rate Limiting with Spring Boot​

Here's an example of how you might implement rate limiting for cache access in a Spring Boot application using the Bucket4j library:

Add Dependencies​

<dependency>
<groupId>com.github.vladimir-bukhtoyarov</groupId>
<artifactId>bucket4j-core</artifactId>
<version>7.5.0</version>
</dependency>

Rate Limiting Configuration​

import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.Refill;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

@Configuration
public class RateLimitingConfig {

@Bean
public Bucket cacheRateLimiter() {
Bandwidth limit = Bandwidth.classic(100, Refill.greedy(100, Duration.ofMinutes(1)));
return Bucket4j.builder().addLimit(limit).build();
}
}

Service Implementation with Rate Limiting​

import io.github.bucket4j.Bucket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

@Autowired
private Bucket cacheRateLimiter;

@Cacheable(value = "userCache", key = "#userId")
public User getUserById(Long userId) {
if (cacheRateLimiter.tryConsume(1)) {
// Fetch user from database
return fetchUserFromDatabase(userId);
} else {
throw new RuntimeException("Rate limit exceeded");
}
}

private User fetchUserFromDatabase(Long userId) {
// Database query logic
return new User();
}
}

Explanation​

  1. Bucket4j Configuration: The Bucket4j library is used to configure a rate limiter with a limit of 100 requests per minute.
  2. Service Implementation: The getUserById method checks if the rate limit has been exceeded before fetching the user from the database. If the limit is exceeded, it throws an exception.

Conclusion​

While reading from a memory cache is fast and should not be a bottleneck, implementing rate limiting can provide several benefits, including resource management, preventing cache stampedes, ensuring fairness, and enhancing security. By using libraries like Bucket4j, you can easily implement rate limiting in your Spring Boot application to manage cache access effectively.


Conclusion​

Memory caching is a powerful tool for improving the performance and scalability of Spring Boot applications in a microservice architecture. By understanding the principles of cache design and implementing best practices, you can effectively manage cache performance, consistency, and reliability in real-life projects.

This article provides a comprehensive guide to memory cache design and implementation in Spring Boot, covering various scenarios and best practices. Use the provided sample code and diagrams to implement efficient caching in your microservice architecture.

Deep Dive into OAuth 2.0 and OpenID Connect

· 6 min read

Introduction​

In the modern web ecosystem, securing user data and managing authentication and authorization are critical tasks. OAuth 2.0 and OpenID Connect (OIDC) are two widely adopted standards that help developers achieve these goals. OAuth 2.0 focuses on authorization, while OpenID Connect extends OAuth 2.0 to provide authentication. This article will delve into the intricacies of both protocols, exploring their architecture, components, and practical applications.

OAuth 2.0: The Authorization Framework​

1.1 Overview​

OAuth 2.0 is an authorization framework that enables third-party applications to obtain limited access to a user's resources without exposing the user's credentials. It is designed to work across different platforms and environments, including web applications, mobile apps, and APIs.

1.2 Key Components​

+-------------------+ +-------------------+ +-------------------+
| Resource Owner | | Client | | Authorization |
| (User) | | (Application) | | Server |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Authorization Request | |
|-------------------------->| |
| | (2) Redirect to Auth Server|
| |-------------------------->|
| | |
| | (3) User Authentication |
| |<--------------------------|
| | |
| | (4) Authorization Grant |
| |<--------------------------|
| | |
| | (5) Access Token Request |
| |-------------------------->|
| | |
| | (6) Access Token Response|
| |<--------------------------|
| | |
| (7) Access Resource | |
|<--------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| Resource Server | | Client | | Authorization |
| (API) | | (Application) | | Server |
+-------------------+ +-------------------+ +-------------------+

1.3 Authorization Grant Types​

OAuth 2.0 defines several grant types, each suited for different use cases:

  • Authorization Code: Used for server-side web applications. The client receives an authorization code from the authorization server and exchanges it for an access token.
  • Implicit: Used for client-side web applications. The access token is returned directly to the client.
  • Resource Owner Password Credentials: Used when the client has a trusted relationship with the resource owner (e.g., a mobile app).
  • Client Credentials: Used for machine-to-machine communication where the client itself is the resource owner.
  • Device Code: Used for devices with limited input capabilities (e.g., smart TVs).

1.4 Access Tokens and Refresh Tokens​

  • Access Token: A credential that the client uses to access the resource server. It has a limited lifetime and is typically short-lived.
  • Refresh Token: A long-lived token that the client can use to obtain a new access token when the current one expires.

1.5 Security Considerations​

  • Token Storage: Access tokens should be stored securely, especially in client-side applications.
  • Token Expiry: Access tokens should have a short expiration time to minimize the risk of misuse.
  • Token Revocation: Mechanisms should be in place to revoke tokens if they are compromised.

OpenID Connect: The Authentication Layer​

2.1 Overview​

OpenID Connect (OIDC) is an authentication layer built on top of OAuth 2.0. It allows clients to verify the identity of the end-user based on the authentication performed by an authorization server. OIDC adds an ID token, which contains information about the authenticated user.

2.2 Key Components​

+-------------------+ +-------------------+ +-------------------+
| Resource Owner | | Client | | Authorization |
| (User) | | (Application) | | Server |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Authorization Request | |
|-------------------------->| |
| | (2) Redirect to Auth Server|
| |-------------------------->|
| | |
| | (3) User Authentication |
| |<--------------------------|
| | |
| | (4) Authorization Grant |
| |<--------------------------|
| | |
| | (5) Access Token Request |
| |-------------------------->|
| | |
| | (6) Access Token Response|
| |<--------------------------|
| | |
| (7) Access Resource | |
|<--------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| Resource Server | | Client | | Authorization |
| (API) | | (Application) | | Server |
+-------------------+ +-------------------+ +-------------------+
| | |
| | (8) ID Token |
| |<--------------------------|
| | |
| (9) UserInfo Request | |
|<--------------------------| |
| | |
| (10) UserInfo Response | |
|<--------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| Resource Server | | Client | | Authorization |
| (API) | | (Application) | | Server |
+-------------------+ +-------------------+ +-------------------+

2.3 Authentication Flows​

  • Authorization Code Flow: Similar to OAuth 2.0's authorization code grant, but with the addition of the ID token.
  • Implicit Flow: Similar to OAuth 2.0's implicit grant, but with the addition of the ID token.
  • Hybrid Flow: Combines aspects of both the authorization code and implicit flows.

2.4 Claims and Scopes​

  • Claims: Information about the authenticated user, such as name, email, and profile picture.
  • Scopes: Permissions requested by the client, such as openid, profile, email, and address.

2.5 Security Considerations​

  • Token Validation: Clients must validate ID tokens to ensure they are authentic and have not been tampered with.
  • Scope Management: Clients should request only the scopes necessary for their functionality.
  • Session Management: Mechanisms should be in place to manage user sessions and handle logout.

Practical Applications​

3.1 Single Sign-On (SSO)​

OAuth 2.0 and OpenID Connect enable Single Sign-On (SSO), allowing users to authenticate once and access multiple applications without re-entering their credentials. This is particularly useful in enterprise environments where users need to access multiple internal applications.

3.2 API Authorization​

OAuth 2.0 is widely used to secure APIs by providing access tokens that grant limited access to resources. This is essential for building secure microservices architectures.

3.3 Mobile and IoT Applications​

OAuth 2.0's device code grant type is particularly useful for devices with limited input capabilities, such as smart TVs and IoT devices. It allows users to authenticate on a secondary device (e.g., a smartphone) and grant access to the primary device.

3.4 Federated Identity​

OpenID Connect enables federated identity, allowing users to authenticate using their existing credentials from a trusted identity provider (e.g., Google, Facebook). This reduces the need for users to create new accounts and manage multiple sets of credentials.

Conclusion​

OAuth 2.0 and OpenID Connect are powerful tools for securing modern web applications. OAuth 2.0 provides a flexible framework for authorization, while OpenID Connect adds an authentication layer on top of it. Together, they enable secure, scalable, and user-friendly authentication and authorization solutions.

Understanding the intricacies of these protocols is essential for developers building secure applications in today's interconnected world. By leveraging OAuth 2.0 and OpenID Connect, developers can ensure that their applications are both secure and user-friendly.

References​

This article provides a comprehensive overview of OAuth 2.0 and OpenID Connect, covering their architecture, components, and practical applications. By understanding these protocols, developers can build secure and scalable applications that meet the demands of today's digital landscape.

Deep Dive into Spring Boot and Quarkus

· 6 min read

Introduction​

Spring Boot and Quarkus are two of the most popular frameworks for building Java applications. Both frameworks aim to simplify the development process and provide robust solutions for modern application development. However, they have different philosophies and approaches. This article will provide a detailed comparison of Spring Boot and Quarkus, exploring their architecture, performance, ecosystem, and community support.

Architecture​

2.1 Overview​

Spring Boot​

Spring Boot is built on top of the Spring framework and provides a streamlined way to create stand-alone, production-grade Spring-based applications. It leverages the Spring ecosystem to offer a wide range of features out of the box.

Quarkus​

Quarkus is a Kubernetes-native Java framework designed for OpenJDK HotSpot and GraalVM. It is optimized for low memory usage and fast startup times, making it ideal for cloud-native applications.

2.2 Microservices​

Spring Boot​

Spring Boot is well-suited for building microservices. It provides built-in support for service discovery, configuration management, and circuit breakers through Spring Cloud Kubernetes, which integrates with Kubernetes' native service discovery mechanisms.

+-------------------+ +-------------------+ +----------------------------------+
| Spring Boot | | Spring Cloud | | Kubernetes |
| Microservice | | Kubernetes | | (Service Discovery and Config |
+-------------------+ +-------------------+ +----------------------------------+
| | |
| (1) Service Discovery | |
|-------------------------->| |
| | (2) Configuration Fetch |
| |-------------------------->|
| | |
| (3) Circuit Breaker | |
|<--------------------------| |
| | |
+-------------------+ +-------------------+ +--------------------------------+
| Spring Boot | | Spring Cloud | | Kubernetes |
| Microservice | | Kubernetes | | (Service Discovery and Config |
+-------------------+ +-------------------+ +--------------------------------+

Quarkus​

Quarkus also supports microservices with extensions for service discovery, configuration management, and fault tolerance. It integrates well with Kubernetes and provides native support for GraalVM.

+-------------------+ +-------------------+ +-------------------+
| Quarkus | | Kubernetes | | GraalVM |
| Microservice | | (Service Discovery| | (Native Image) |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Service Discovery | |
|-------------------------->| |
| | (2) Configuration Fetch |
| |-------------------------->|
| | |
| (3) Native Image Build | |
|<--------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| Quarkus | | Kubernetes | | GraalVM |
| Microservice | | (Service Discovery| | (Native Image) |
+-------------------+ +-------------------+ +-------------------+

2.3 Dependency Injection​

Spring Boot​

Spring Boot uses the Spring Framework's dependency injection mechanism, which is based on the Inversion of Control (IoC) principle.

@Service
public class MyService {
public String getMessage() {
return "Hello, Spring Boot!";
}
}

@RestController
public class MyController {
@Autowired
private MyService myService;

@GetMapping("/message")
public String getMessage() {
return myService.getMessage();
}
}

Quarkus​

Quarkus uses the Contexts and Dependency Injection (CDI) standard for dependency injection, which is part of the Java EE specification.

@ApplicationScoped
public class MyService {
public String getMessage() {
return "Hello, Quarkus!";
}
}

@Path("/message")
public class MyResource {
@Inject
MyService myService;

@GET
@Produces(MediaType.TEXT_PLAIN)
public String getMessage() {
return myService.getMessage();
}
}

2.4 Reactive Programming​

Spring Boot​

Spring Boot supports reactive programming through Spring WebFlux, which is built on top of Project Reactor.

@RestController
public class MyReactiveController {
@GetMapping("/reactive-message")
public Mono<String> getReactiveMessage() {
return Mono.just("Hello, Reactive Spring Boot!");
}
}

Quarkus​

Quarkus supports reactive programming through its Reactive Streams Operators and integrates well with frameworks like Vert.x.

@Path("/reactive-message")
public class MyReactiveResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public Uni<String> getReactiveMessage() {
return Uni.createFrom().item("Hello, Reactive Quarkus!");
}
}

Performance​

3.1 Startup Time​

Spring Boot​

Spring Boot applications typically have a longer startup time due to the extensive initialization of the Spring framework.

Quarkus​

Quarkus applications have a much faster startup time, especially when using GraalVM to build native images.

3.2 Memory Usage​

Spring Boot​

Spring Boot applications generally consume more memory due to the heavyweight nature of the Spring framework.

Quarkus​

Quarkus applications consume less memory, making them more efficient for containerized environments.

3.3 Runtime Efficiency​

Spring Boot​

Spring Boot applications are optimized for traditional Java runtime environments.

Quarkus​

Quarkus applications are optimized for modern, cloud-native environments and can take advantage of GraalVM for native execution.

Ecosystem and Community​

4.1 Spring Ecosystem​

Spring Boot benefits from the extensive Spring ecosystem, which includes Spring Data, Spring Security, Spring Cloud Kubernetes, and many other modules.

4.2 Quarkus Ecosystem​

Quarkus has a growing ecosystem with extensions for various technologies, including databases, messaging systems, and cloud services.

4.3 Community Support​

Spring Boot​

Spring Boot has a large and active community, with extensive documentation, tutorials, and third-party libraries.

Quarkus​

Quarkus has a rapidly growing community, with increasing support from Red Hat and other contributors.

Sample Code​

5.1 Spring Boot Example​

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class SpringBootExample {
public static void main(String[] args) {
SpringApplication.run(SpringBootExample.class, args);
}
}

@RestController
class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}

5.2 Quarkus Example​

import io.quarkus.runtime.Quarkus;
import io.quarkus.runtime.annotations.QuarkusMain;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@QuarkusMain
public class QuarkusExample {
public static void main(String[] args) {
Quarkus.run(args);
}
}

@Path("/hello")
public class HelloResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello, Quarkus!";
}
}

Conclusion​

Both Spring Boot and Quarkus are powerful frameworks for building Java applications, each with its own strengths and weaknesses. Spring Boot offers a mature and feature-rich ecosystem, making it a great choice for a wide range of applications. Quarkus, on the other hand, is optimized for modern, cloud-native environments and provides excellent performance and efficiency.

Choosing between Spring Boot and Quarkus depends on the specific requirements of your project, including performance, ecosystem, and community support. By understanding the differences and capabilities of both frameworks, you can make an informed decision that best suits your needs.

References​


This article provides a comprehensive comparison of Spring Boot and Quarkus, covering their architecture, performance, ecosystem, and community support. By understanding these frameworks, developers can choose the best tool for their projects and build efficient and scalable applications.

Kubernetes StatefulSet and Deployment

· 4 min read

In Kubernetes, StatefulSet and Deployment are two important concepts for managing workloads, each tailored to specific types of applications.


Overview: StatefulSet vs. Deployment​

1. Deployment​

  • A Deployment manages stateless applications, where each instance (Pod) is identical and can be easily replaced without any dependency on the previous instance’s state.
  • It allows for easy scaling up or down, rolling updates, and rollback.
  • Deployments are ideal for applications that don’t need unique identities or persistent storage tied to each Pod.

2. StatefulSet​

  • A StatefulSet is used to manage stateful applications where each Pod maintains a unique identity and persistent storage.
  • Pods created by StatefulSets are given fixed identities, which are essential for applications that depend on stable network IDs or persistent data volumes.
  • It ensures an ordered and predictable sequence for Pod creation, deletion, and scaling operations, making it suitable for stateful applications.

Key Differences Between Deployment and StatefulSet​

FeatureDeploymentStatefulSet
Use CaseStateless applicationsStateful applications
Pod IdentityAll Pods are identicalEach Pod has a unique, stable identity
Persistent StorageNot tied to specific Pods; ephemeral by defaultPersistent Volume Claims (PVC) linked to each Pod
Pod ManagementUnordered Pod creation, deletion, or scalingOrdered Pod creation, deletion, and scaling
ScalingIndependent scaling; any Pod can be replacedScaling maintains Pod identity; Pods are replaced in order
NetworkingPods are accessed via a common service nameEach Pod gets a unique DNS endpoint

When to Use Deployment vs. StatefulSet​

Deployment Use Cases:​

  • Stateless Applications: For applications that don’t require persistent storage or a unique identity, like web servers, RESTful APIs, front-end services, and microservices.
  • Scale-Out Workloads: When you need to scale the application horizontally with many replicas, such as with compute-intensive tasks (e.g., image processing).
  • CI/CD Pipelines: Deployment objects are suitable for managing frequent updates and rollbacks in stateless applications.
  • Load-Balanced Services: For applications where all instances serve the same purpose and can respond to requests in a round-robin or load-balanced fashion.

Example:

apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
spec:
replicas: 3
selector:
matchLabels:
app: frontend
template:
metadata:
labels:
app: frontend
spec:
containers:
- name: frontend
image: nginx:latest

StatefulSet Use Cases:​

  • Databases: For databases like MySQL, PostgreSQL, or Cassandra, where each instance needs persistent storage and must be able to rejoin the cluster with the same identity after a restart.
  • Distributed Applications: For clustered or distributed applications that need stable network identities, such as Apache Kafka, Zookeeper, or Redis in a master-slave configuration.
  • Ordered Processing: For workloads that require ordered startup and shutdown, maintaining consistency across the replicas.
  • Persistent Storage Requirements: For applications that need durable storage across restarts, such as analytics applications or logging systems that rely on data persistence.

Example:

apiVersion: apps/v1
kind: StatefulSet
metadata:
name: database
spec:
serviceName: "database-service"
replicas: 3
selector:
matchLabels:
app: database
template:
metadata:
labels:
app: database
spec:
containers:
- name: db
image: mysql:5.7
volumeMounts:
- name: data
mountPath: /var/lib/mysql
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 10Gi

Real-World Scenarios​

  1. Use StatefulSet for a Database Cluster:

    • Applications like Cassandra or MongoDB require that each node (or replica) has a unique identifier, stable storage, and maintains a specific order in the cluster.
    • StatefulSet will ensure each database Pod keeps its persistent storage (e.g., transaction logs) and its network identity, allowing for seamless cluster membership and fault recovery.
  2. Use Deployment for a Web Application Front-End:

    • Stateless applications like front-end services, web servers, and microservices, which don’t require persistent storage, are best managed by Deployments.
    • Deployments allow fast horizontal scaling to handle fluctuating traffic, automated rolling updates to support frequent releases, and easy recovery from failure.
  3. Use StatefulSet for Messaging Queues:

    • Applications like Kafka, RabbitMQ, and Redis often require ordered replica management, durable storage, and unique identifiers for cluster consistency.
    • StatefulSet will ensure that the pods are started in sequence and keep their storage intact across restarts.
  4. Use Deployment for API Gateways:

    • API Gateways, which act as proxies or load balancers for backend services, are stateless by design. Deployments allow for fast failover and load distribution while handling updates without data dependency concerns.

In summary, choose StatefulSet for workloads needing state persistence, stable identities, and ordered management (typically databases and clustered applications). Opt for Deployment for stateless, load-balanced, and horizontally scalable applications that need easy updates and high availability.