npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

cache-composer

v1.0.0

Published

Advanced multi-layer caching with memory, Redis, and file storage. Features automatic invalidation, cache warming, and analytics.

Readme

Cache Composer

npm version License: MIT GitHub

Advanced multi-layer caching library with memory, Redis, and file storage. Features automatic invalidation strategies, cache warming, and comprehensive analytics.

Features

  • Multi-Layer Caching: Memory → Redis → File system with automatic promotion
  • Invalidation Strategies: LRU, LFU, TTL-based, and manual invalidation
  • Cache Warming: Pre-populate cache on startup
  • Tag-Based Invalidation: Group and invalidate related cache entries
  • Analytics: Hit/miss rates, access times, and per-layer statistics
  • Universal: Works in Node.js, React, and browser environments
  • TypeScript: Full type safety and IntelliSense support

Installation

npm install cache-composer

For Redis support:

npm install cache-composer ioredis

Quick Start

Basic Usage (Memory Only)

import { CacheComposer } from 'cache-composer';

const cache = new CacheComposer();

// Set a value
await cache.set('user:123', { name: 'John', age: 30 });

// Get a value
const user = await cache.get('user:123');

// Get or set with loader
const data = await cache.getOrSet('expensive-data', async () => {
  return await fetchExpensiveData();
}, { ttl: 60000 }); // 1 minute TTL

Multi-Layer Configuration

import { CacheComposer } from 'cache-composer';
import Redis from 'ioredis';

const redis = new Redis();

const cache = new CacheComposer({
  memory: {
    enabled: true,
    maxSize: 1000,
    ttl: 60000, // 1 minute
    invalidation: { type: 'lru' }
  },
  redis: {
    enabled: true,
    client: redis,
    ttl: 3600000 // 1 hour
  },
  file: {
    enabled: true,
    directory: '.cache',
    ttl: 86400000 // 24 hours
  },
  analytics: true
});

React Usage

import { CacheComposer } from 'cache-composer';
import { useEffect, useState } from 'react';

const cache = new CacheComposer();

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    cache.getOrSet(`user:${userId}`, async () => {
      const response = await fetch(`/api/users/${userId}`);
      return response.json();
    }, { ttl: 300000 }).then(setUser);
  }, [userId]);

  return <div>{user?.name}</div>;
}

API Reference

Core Methods

get<T>(key: string): Promise<T | null>

Retrieve a value from cache.

set<T>(key: string, value: T, options?: CacheOptions): Promise<void>

Store a value in cache.

Options:

  • ttl: Time to live in milliseconds
  • tags: Array of tags for grouped invalidation

delete(key: string): Promise<boolean>

Remove a key from cache.

clear(): Promise<void>

Clear all cache entries.

getOrSet<T>(key: string, loader: () => Promise<T>, options?: CacheOptions): Promise<T>

Get from cache or load and cache if missing.

Advanced Methods

mget<T>(keys: string[]): Promise<Map<string, T>>

Get multiple keys at once.

mset<T>(entries: Map<string, T>, options?: CacheOptions): Promise<void>

Set multiple keys at once.

deleteByTag(tag: string): Promise<number>

Delete all entries with a specific tag.

invalidatePattern(pattern: RegExp): Promise<number>

Delete all keys matching a pattern.

touch(key: string, ttl?: number): Promise<boolean>

Refresh TTL for a key.

Analytics

getStats(): CacheStats

Get comprehensive cache statistics.

const stats = cache.getStats();
console.log(`Hit rate: ${(stats.hitRate * 100).toFixed(2)}%`);
console.log(`Total requests: ${stats.totalRequests}`);
console.log(`Memory layer hits: ${stats.layerStats.memory?.hits}`);

resetStats(): void

Reset analytics counters.

Advanced Features

Cache Warming

Pre-populate cache on startup:

const cache = new CacheComposer({
  warmup: {
    enabled: true,
    keys: [
      {
        key: 'config',
        loader: async () => await loadConfig(),
        options: { ttl: 3600000 }
      },
      {
        key: 'popular-items',
        loader: async () => await fetchPopularItems()
      }
    ]
  }
});

Tag-Based Invalidation

Group related cache entries:

// Set with tags
await cache.set('user:123', userData, { tags: ['users', 'profile'] });
await cache.set('user:456', userData2, { tags: ['users', 'profile'] });

// Invalidate all user-related cache
await cache.deleteByTag('users');

Invalidation Strategies

const cache = new CacheComposer({
  memory: {
    enabled: true,
    maxSize: 1000,
    invalidation: { 
      type: 'lru' // or 'lfu', 'ttl', 'manual'
    }
  }
});
  • LRU (Least Recently Used): Evicts least recently accessed items
  • LFU (Least Frequently Used): Evicts least frequently accessed items
  • TTL: Time-based expiration
  • Manual: No automatic eviction

Performance Tips

  1. Layer Order: Memory → Redis → File provides optimal performance
  2. TTL Strategy: Use shorter TTL for memory, longer for Redis/File
  3. Batch Operations: Use mget/mset for multiple keys
  4. Analytics: Monitor hit rates to optimize cache configuration

Examples

Check out the examples directory for more use cases:

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT © codecrypt1112

Links