Sitemap
Murat Aslan

Murat Aslan

Forward Deployed Engineer https://linktr.ee/murataslan

Cache Invalidation

5 min readMar 15, 2023

Cache invalidation refers to the process of removing or updating cached data when the underlying data has changed. Caching is a commonly used technique in software development where frequently accessed data is stored in a temporary storage location, called a cache, to improve performance.

However, when the underlying data changes, the cached data may no longer be valid and can lead to incorrect results. Therefore, it is important to invalidate or update the cache to ensure that the data remains consistent with the updated information.

Here are a few real-world scenarios and examples of cache invalidation:

E-commerce website

Consider an e-commerce website that displays product prices on a product listing page. The prices are fetched from a database and cached to improve performance. If the price of a product is updated in the database, the cached price will be outdated and incorrect. Therefore, the cache needs to be invalidated or updated to reflect the latest price.

Example in Python:

import cache

def get_product_price(product_id):
# Check if the price is cached
price = cache.get(product_id)
if price is not None:
return price

# If the price is not cached, fetch it from the database
price = fetch_product_price_from_database(product_id)

# Cache the price for future use
cache.set(product_id, price)

return price

def update_product_price(product_id, new_price):
# Update the price in the database
update_product_price_in_database(product_id, new_price)

# Invalidate the cache for the product price
cache.invalidate(product_id)

2. Social media feed

Consider a social media platform that displays a user’s feed on their home page. The feed is generated based on the user’s friends and their posts, which are fetched from a database and cached to improve performance. If a friend makes a new post, the cached feed will be outdated and incorrect. Therefore, the cache needs to be invalidated or updated to reflect the latest posts.

Example in JavaScript:

const cache = require('cache');

function get_user_feed(user_id) {
// Check if the feed is cached
const feed = cache.get(user_id);
if (feed) {
return feed;
}

// If the feed is not cached, fetch it from the database
const friends = fetch_user_friends_from_database(user_id);
const posts = fetch_posts_from_database(friends);
const feed = generate_feed(posts);

// Cache the feed for future use
cache.set(user_id, feed);

return feed;
}

function add_new_post(user_id, post) {
// Add the new post to the database
add_post_to_database(user_id, post);

// Invalidate the cache for the user's feed
cache.invalidate(user_id);
}

In both examples, when new data is added or updated, the cache needs to be invalidated to ensure that the cached data remains consistent with the updated information. By doing so, the performance is maintained while ensuring data consistency.

Banking application

Consider a banking application that displays a customer’s account balance. The account balance is fetched from a database and cached to improve performance. If a transaction is made on the account, such as a deposit or withdrawal, the cached balance will be outdated and incorrect. Therefore, the cache needs to be invalidated or updated to reflect the latest balance.

Get Murat Aslan’s stories in your inbox

Join Medium for free to get updates from this writer.

Example in Java:

import cache.Cache;

public class BankingApplication {
private Cache cache = new Cache();
private AccountDatabase accountDatabase = new AccountDatabase();

public double getAccountBalance(int accountId) {
// Check if the balance is cached
Double balance = cache.get(accountId);
if (balance != null) {
return balance;
}

// If the balance is not cached, fetch it from the database
balance = accountDatabase.getAccountBalance(accountId);

// Cache the balance for future use
cache.set(accountId, balance);

return balance;
}

public void makeTransaction(int accountId, double amount) {
// Make the transaction on the account
accountDatabase.makeTransaction(accountId, amount);

// Invalidate the cache for the account balance
cache.invalidate(accountId);
}
}

Weather application

Consider a weather application that displays the current temperature at a particular location. The temperature is fetched from a third-party API and cached to improve performance. If the temperature at the location changes, the cached temperature will be outdated and incorrect. Therefore, the cache needs to be invalidated or updated to reflect the latest temperature.

Example in Python:

import cache
import weather_api

def get_current_temperature(location):
# Check if the temperature is cached
temperature = cache.get(location)
if temperature is not None:
return temperature

# If the temperature is not cached, fetch it from the API
temperature = weather_api.get_current_temperature(location)

# Cache the temperature for future use
cache.set(location, temperature)

return temperature

def update_temperature(location):
# Fetch the latest temperature from the API
temperature = weather_api.get_current_temperature(location)

# Update the cache with the latest temperature
cache.set(location, temperature)
}

In these examples, cache invalidation ensures that the cached data remains consistent with the updated information, ensuring accuracy and data integrity.

ASP.NET web application

Consider an ASP.NET web application that displays a list of products on a product listing page. The products are fetched from a database and cached to improve performance. If a new product is added to the database, the cached product list will be outdated and incorrect. Therefore, the cache needs to be invalidated or updated to reflect the latest product list.

Example in C#:

using System.Web.Caching;

public class ProductListingPage : System.Web.UI.Page {
private const string ProductListCacheKey = "ProductList";
private ProductDatabase productDatabase = new ProductDatabase();

protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
// Check if the product list is cached
var productList = Cache[ProductListCacheKey] as List<Product>;
if (productList != null) {
BindProductList(productList);
return;
}

// If the product list is not cached, fetch it from the database
productList = productDatabase.GetProductList();

// Cache the product list for future use
Cache[ProductListCacheKey] = productList;

BindProductList(productList);
}
}

protected void AddProductButton_Click(object sender, EventArgs e) {
// Add the new product to the database
productDatabase.AddProduct(new Product {
Name = ProductNameTextBox.Text,
Price = decimal.Parse(ProductPriceTextBox.Text)
});

// Invalidate the cache for the product list
Cache.Remove(ProductListCacheKey);
}
}

In this example, when a new product is added to the database, the cache for the product list needs to be invalidated to ensure that the cached data remains consistent with the updated information.

Windows Forms application

Consider a Windows Forms application that displays a list of customers in a DataGridView control. The customer data is fetched from a database and cached to improve performance. If a customer’s information is updated in the database, the cached customer data will be outdated and incorrect. Therefore, the cache needs to be invalidated or updated to reflect the latest customer data.

Example in C#:

using System.Windows.Forms;

public class CustomerListForm : Form {
private const string CustomerListCacheKey = "CustomerList";
private CustomerDatabase customerDatabase = new CustomerDatabase();

public void LoadCustomerList() {
// Check if the customer list is cached
var customerList = Cache[CustomerListCacheKey] as List<Customer>;
if (customerList != null) {
BindCustomerList(customerList);
return;
}

// If the customer list is not cached, fetch it from the database
customerList = customerDatabase.GetCustomerList();

// Cache the customer list for future use
Cache[CustomerListCacheKey] = customerList;

BindCustomerList(customerList);
}

public void UpdateCustomer(Customer customer) {
// Update the customer in the database
customerDatabase.UpdateCustomer(customer);

// Invalidate the cache for the customer list
Cache.Remove(CustomerListCacheKey);
}
}

In this example, when a customer’s information is updated in the database, the cache for the customer list needs to be invalidated to ensure that the cached data remains consistent with the updated information.

--

--