Skip to main content
Version: Next

invalidate Function

One of the most important aspects of caching is knowing when to remove or invalidate cached data. CommandKit provides a dedicated invalidate function that allows you to explicitly remove specific entries from your cache.

Basic Usage

The invalidate function removes a specific entry from the cache based on its key. This is particularly useful when you have updated the source data and need to ensure the next request retrieves fresh data instead of serving stale cached content.

import { invalidate } from '@commandkit/cache';

// Remove a specific cache entry by its key
await invalidate('user:123');

When to Use Cache Invalidation

Cache invalidation is essential in the following scenarios:

  1. After Data Updates

    When you modify data that is cached elsewhere in your application, you should invalidate the related cache to prevent serving outdated information:

    async function updateUserProfile(userId: string, newData: UserProfile) {
    // Update the database
    await database.updateUser(userId, newData);

    // Invalidate the cached user profile
    await invalidate(`user:${userId}`);
    }
  2. After Batch Operations

    When performing operations that affect multiple cached items:

    async function resetUserRanks(guildId: string) {
    // Reset all ranks in database
    await database.resetRanks(guildId);

    // Invalidate the leaderboard cache for this guild
    await invalidate(`leaderboard:${guildId}`);

    // You might also need to invalidate individual user caches
    const users = await database.getGuildMembers(guildId);
    await Promise.all(
    users.map((user) => invalidate(`user:${guildId}:${user.id}`)),
    );
    }
  3. On Event-Driven Changes

    Invalidate cache when external events might affect your data:

    // Discord event handler
    client.on('guildMemberUpdate', async (oldMember, newMember) => {
    // Invalidate any cache related to this member
    await invalidate(`member:${newMember.guild.id}:${newMember.id}`);
    });

Multiple Key Invalidation

The invalidate function can also accept an array of keys to invalidate multiple cache entries at once:

import { invalidate } from '@commandkit/cache';

// Invalidate multiple cache entries
await invalidate(['user:123', 'user:123:profile', 'leaderboard:guild:456']);

Combining with Other Cache Functions

You can use invalidate alongside other caching functions for more complex scenarios:

import { invalidate, revalidate } from '@commandkit/cache';

async function processMemberChange(guildId: string, memberId: string) {
// Invalidate the user's profile cache
await invalidate(`member:${guildId}:${memberId}`);

// Revalidate the guild leaderboard (fetch fresh data and cache it)
const freshLeaderboard = await revalidate(`leaderboard:${guildId}`);

return freshLeaderboard;
}

Error Handling

When invalidating cache, it's good practice to include error handling:

import { invalidate } from '@commandkit/cache';

try {
await invalidate('user:123');
console.log('Cache invalidated successfully');
} catch (error) {
console.error('Failed to invalidate cache:', error);
// Handle error gracefully
}

Best Practices

  1. Be Strategic About Invalidation

    Invalidate cache only when necessary. Excessive invalidation reduces the benefits of caching.

  2. Maintain Consistent Keys

    Use the same key format when setting and invalidating cache to ensure you're targeting the correct entries.

  3. Group Related Invalidations

    When multiple related cache entries need invalidation, group them together for better performance.

  4. Consider Cascading Effects

    Remember that invalidating one cache entry might require invalidating related entries that depend on the same data.

  5. Use Invalidation in Event Handlers

    Add cache invalidation to your event handlers to keep cache in sync with real-time data changes.