REST API Caching Methods

Caching is a powerful optimization methods that improves the efficiency, scalability and performance of Rest APIs. It helps reduce the load on database, minimizes redundant computations and speed up response times by storing frequently request data closer to the client or server.

1. Application Layer Caching - Using Redis for Fast data retrieval

  • Store frequently used data at in memory database (Redis) for faster retrieval of data or Quick access
  • Maintain the unique key value identified pair for uniqueness data

e.g. : Sample Java program
import redis.clients.jedis.Jedis;
public class UserService {

private Jedis redisClient = new Jedis("localhost");

public String getUserProfile(String userId) {
//Check if the user profile exist in the cache
String cachedProfile = redisClient.get(userId);
    if(cachedProfile != null) {
        System.out.println("Cache found!");
        return cachedProfile; 
        }

        //Get data from actual database
        System.out.println("Cache Missed... Fetching it from Actual database!!!");
        String userProfile = fetchFromDatabase(userId);
        
        // Cache the result with TTL of 5 minutes
        redisClient.setex(userId, 300, userProfile);
        return userProfile;
    }

    public String fetchFromDatabase(String userId) {
        // simulated database fetch
        return "userProfile for " + userId;
    }
}


2. Request Level Caching - Storing Full API responses - Caching predictable GET responses

  • Clients receive updated data only based on condition, only when necessary.
  • Read heavy Rest APIs - APIs with frequent GET requests with mostly static data
  • Expensive Queries -  Endpoints that involves  complex computations or large database queries
  • Paginated data - Responses with data like page or limit 

3. Conditional Caching - ETag and Last modified for efficient API calls.

  • Efficiently updating data with conditions
  • Handled via HTTP header with ETag and last modified values
  • ETag - Unique identifier for a resource version
  • Last-Modified - Time-Stamp of the last update to a resource


4. Cache InvalidationWrite through, Write behind and TTL based eviction

Removing inconsistent or outdated old data to maintain accuracy. Or sync with actual data


5. Layered Caching - Browser, CDN & Server-side Optimization

Combined the layers integrating browser, CDN, & application cache

Comments

Popular posts from this blog

PUTTY - The server's host key is not cached in the registry cache

OIM-12c Installation - FMW - SOA - IDM

SAML & OAuth 2.0