cachana
v2.0.0
Published
High-performance in-memory cache with TTL, automatic cleanup, memory limits, and REST API
Maintainers
Readme
🧠 Cachana
Cachana is a high-performance, in-memory key-value cache with TTL (Time-To-Live), automatic cleanup, memory limits, CLI tools, REST API server, and a robust JavaScript client.
Ideal for fast caching, development utilities, remote memory storage, and production applications.
🚀 Features
- ⚡ High-performance in-memory key-value store with optimized operations
- ⏱️ Built-in TTL expiration (per-entry) with automatic background cleanup
- 💾 Memory management with configurable size limits and LRU eviction
- 📊 Statistics tracking - hits, misses, and evictions
- 💻 CLI tools for shell-based access with comprehensive error handling
- 🌐 REST API with input validation and batch operations
- 🧪 Robust JavaScript client with retry logic and timeout handling
- 🔄 Batch operations for improved performance
- 🛡️ Error handling and graceful shutdown
🛠️ Installation
npm install cachanaFor global CLI access:
npm install -g cachana📖 Usage
Programmatic Usage (Node.js)
Core Cachana Class
import { Cachana } from "cachana";
// Basic usage with default 60-second TTL
const cache = new Cachana();
// Advanced configuration
const cache = new Cachana(30000, {
maxSize: 1000, // Maximum number of entries
cleanupInterval: 15000 // Cleanup expired entries every 15 seconds
});Methods
| Method | Description |
| ------------------- | ---------------------------------------- |
| set(key, value, ttl?) | Set a value with optional custom TTL |
| get(key) | Get a value or null if expired/missing |
| has(key) | Returns true if key exists and is valid |
| delete(key) | Removes a key, returns true if existed |
| clear() | Clears entire cache |
| getAll() | Returns all valid key-value pairs |
| size | Number of active (non-expired) keys |
| getStats() | Get cache statistics |
| destroy() | Clean shutdown (stops cleanup timer) |
Example
import { Cachana } from "cachana";
const cache = new Cachana(60000, { maxSize: 100 });
// Set values
cache.set("user:123", { name: "Alice", role: "admin" });
cache.set("session:abc", "active", 30000); // Custom 30s TTL
// Get values
console.log(cache.get("user:123")); // { name: "Alice", role: "admin" }
console.log(cache.has("session:abc")); // true
// Statistics
console.log(cache.getStats()); // { hits: 2, misses: 0, evictions: 0 }
// Cleanup when done
cache.destroy();🖥️ Server & CLI Usage
Start the Server
cachana-server
# or with custom port
PORT=8080 cachana-serverCLI Commands
# Set values
cachana set username alice
cachana set session xyz123 5000 # with 5-second TTL
# Get values
cachana get username # → alice
cachana has session # → ✅ Exists
# Delete and clear
cachana delete username
cachana clear # Remove all keys
# Information
cachana all # Show all keys
cachana size # Show count
cachana stats # Show statistics
# Custom server URL
CACHANA_URL=http://localhost:8080 cachana get username📡 REST API
Default server: http://localhost:7070
| Method | Endpoint | Description |
| ------ | ---------------- | ------------------------------ |
| POST | /set | Set key-value with optional TTL |
| GET | /get/:key | Get value by key |
| GET | /has/:key | Check if key exists |
| DELETE | /delete/:key | Delete key |
| POST | /clear | Clear entire cache |
| GET | /all | Get all valid keys |
| GET | /size | Get cache size |
| GET | /stats | Get cache statistics |
| POST | /batch/set | Set multiple keys at once |
Examples
Set a value:
curl -X POST http://localhost:7070/set \\
-H "Content-Type: application/json" \\
-d '{"key": "session", "value": "abc123", "ttl": 5000}'Batch operations:
curl -X POST http://localhost:7070/batch/set \\
-H "Content-Type: application/json" \\
-d '{
"items": [
{"key": "user1", "value": "Alice"},
{"key": "user2", "value": "Bob", "ttl": 30000}
]
}'Get statistics:
curl http://localhost:7070/stats
# → {"hits": 45, "misses": 12, "evictions": 3}🔗 JavaScript Client
import { CachanaClient } from "cachana/client";
// Basic client
const client = new CachanaClient("http://localhost:7070");
// Client with options
const client = new CachanaClient("http://localhost:7070", {
timeout: 5000, // 5-second timeout
retries: 2 // Retry failed requests twice
});Client Methods
| Method | Description |
| ----------------------- | ---------------------------------- |
| set(key, value, ttl?) | Set a value |
| get(key) | Get a value |
| has(key) | Check existence |
| delete(key) | Delete a key |
| clear() | Clear cache |
| getAll() | Get all entries |
| size() | Get cache size |
| getStats() | Get statistics |
| batchSet(items) | Set multiple keys |
Client Examples
import { CachanaClient } from "cachana/client";
const client = new CachanaClient();
// Basic operations
await client.set("token", "xyz789", 10000);
console.log(await client.get("token")); // 'xyz789'
// Batch operations
const results = await client.batchSet([
{ key: "user1", value: "Alice" },
{ key: "user2", value: "Bob", ttl: 5000 }
]);
// Statistics
const stats = await client.getStats();
console.log(`Hit rate: ${stats.hits / (stats.hits + stats.misses) * 100}%`);🔬 Testing
Start the server:
cachana-serverRun tests:
npm testFor development with auto-restart:
npm run dev⚙️ Configuration
Environment Variables
PORT- Server port (default: 7070)CACHANA_URL- Client/CLI server URL (default: http://localhost:7070)
Constructor Options
const cache = new Cachana(ttl, {
maxSize: 1000, // Max entries before LRU eviction
cleanupInterval: 30000 // Background cleanup frequency (ms)
});📈 Performance Features
- Automatic cleanup - Background removal of expired entries
- Memory limits - LRU eviction prevents unbounded growth
- Optimized operations - Direct map access, no redundant scans
- Batch processing - Set multiple keys in single request
- Connection pooling - Client reuses connections efficiently
- Statistics tracking - Monitor cache performance
🏗️ Project Structure
cachana/
├── src/ # Core cache library
├── server/ # REST API server
├── client/ # JavaScript client
├── bin/ # CLI tools
└── test/ # Test suite📄 License
MIT © 2025 M.Alsouki
🔄 Changelog
v2.0.0
- ⚡ Performance: Automatic cleanup, optimized getAll/size operations
- 💾 Memory management: Size limits with LRU eviction
- 📊 Statistics: Hit/miss/eviction tracking
- 🔄 Batch operations: Set multiple keys efficiently
- 🛡️ Error handling: Comprehensive validation and error recovery
- 🔌 Client improvements: Retry logic, timeouts, additional methods
- 🐛 Bug fixes: URL encoding, proper cleanup, graceful shutdown
