Skip to content

Key Value Cache (KV Cache)

This content is for the 0.6.3 version. Switch to the latest version for up-to-date documentation.

KV Cache provides distributed key-value storage for caching data across applications. The component supports multiple data types including strings, JSON objects, binary data, and streams.

KV Cache stores data with optional expiration times and custom metadata. You can retrieve values with their associated metadata and cache status information. The component handles automatic serialization and provides type-safe access to stored data.

Applications use KV Cache for session storage, configuration caching, and temporary data persistence. The distributed nature ensures consistent access across multiple application instances.

Creating

Configure KV Cache storage in your raindrop.manifest file:

application "demo-app" {
kv_cache "demo-kv-cache" {}
}

Accessing

Access your KV Cache instance through environment bindings in your application code:

export default {
async fetch(request: Request, env: Env) {
// Access the KV Cache instance
const value = await env.demoKvCache.get('user:123');
return new Response(value);
}
}

Core Concepts

Main interfaces:

  • KvCache - Primary interface for storage operations
  • KvCacheListKey - Represents a key with metadata and expiration
  • KvCacheListResult - Result structure for list operations
  • KvCacheGetWithMetadataResult - Value with metadata and cache status

KvCacheListKey

Represents a stored key with its metadata and expiration information:

// Key structure with optional metadata and expiration
interface KvCacheListKey<Metadata, Key extends string = string> {
name: Key; // The key name
expiration?: number; // Unix timestamp for expiration
metadata?: Metadata; // Custom metadata object
}

KvCacheListResult

Contains the results of list operations with pagination support:

// Complete list result
type KvCacheListResult<Metadata, Key extends string = string> = {
list_complete: true;
keys: KvCacheListKey<Metadata, Key>[];
cacheStatus: string | null;
} | {
// Paginated result with cursor
list_complete: false;
keys: KvCacheListKey<Metadata, Key>[];
cursor: string;
cacheStatus: string | null;
}

KvCacheGetWithMetadataResult

Returns value along with metadata and cache status:

// Value with metadata and cache information
interface KvCacheGetWithMetadataResult<Value, Metadata> {
value: Value | null; // The stored value
metadata: Metadata | null; // Associated metadata
cacheStatus: string | null; // Cache hit/miss status
}

System Limits

  • Maximum key size: 512 bytes
  • Maximum value size: 25 MiB
  • Maximum key metadata: 1024 bytes
  • Rate limits: 1 write per second per key, 1000 operations per Service invocation
  • Minimum cacheTTL: 60 seconds
  • Default list operation limit: 1000 items

get

Retrieves a value from storage by key with optional type conversion and caching.

// Basic text retrieval
get(key: Key, options?: Partial<KvCacheGetOptions<undefined>>): Promise<string | null>
// Explicit type specification
get(key: Key, type: 'text'): Promise<string | null>
get<ExpectedValue = unknown>(key: Key, type: 'json'): Promise<ExpectedValue | null>
get(key: Key, type: 'arrayBuffer'): Promise<ArrayBuffer | null>
get(key: Key, type: 'stream'): Promise<ReadableStream | null>
// With options
get(key: Key, options?: KvCacheGetOptions<'text'>): Promise<string | null>
get<ExpectedValue = unknown>(key: Key, options?: KvCacheGetOptions<'json'>): Promise<ExpectedValue | null>
get(key: Key, options?: KvCacheGetOptions<'arrayBuffer'>): Promise<ArrayBuffer | null>
get(key: Key, options?: KvCacheGetOptions<'stream'>): Promise<ReadableStream | null>

Example

Retrieve user data from storage with JSON parsing:

// Get user data as JSON object
const userData = await env.demoKvCache.get<{name: string, email: string}>('user:123', 'json');
if (userData) {
console.log(`User: ${userData.name}`); // Access parsed object properties
}

put

Stores a value in the cache with optional expiration and metadata.

put(
key: Key,
value: string | ArrayBuffer | ArrayBufferView | ReadableStream,
options?: KvCachePutOptions
): Promise<void>
interface KvCachePutOptions {
expiration?: number; // Unix timestamp for expiration
expirationTtl?: number; // TTL in seconds
metadata?: any | null; // Custom metadata object
}

Example

Store user session data with expiration:

// Store session data with 1 hour expiration
const sessionData = JSON.stringify({userId: 123, role: 'admin'});
await env.demoKvCache.put('session:abc123', sessionData, {
expirationTtl: 3600, // 1 hour in seconds
metadata: {created: Date.now()} // Custom metadata
});

list

Returns a list of keys matching optional prefix and pagination criteria.

list<Metadata = unknown>(options?: KvCacheListOptions): Promise<KvCacheListResult<Metadata, Key>>
interface KvCacheListOptions {
limit?: number; // Maximum keys to return (default: 1000)
prefix?: string | null; // Key prefix filter
cursor?: string | null; // Pagination cursor
}

Example

List all user keys with pagination:

// Get first 10 user keys
const result = await env.demoKvCache.list({
prefix: 'user:', // Only keys starting with 'user:'
limit: 10 // Limit to 10 results
});
for (const key of result.keys) {
console.log(`Key: ${key.name}, Expires: ${key.expiration}`); // Process each key
}

getWithMetadata

Retrieves a value along with its metadata and cache status information.

// Basic retrieval with metadata
getWithMetadata<Metadata = unknown>(
key: Key,
options?: Partial<KvCacheGetOptions<undefined>>
): Promise<KvCacheGetWithMetadataResult<string, Metadata>>
// Type-specific retrieval
getWithMetadata<Metadata = unknown>(key: Key, type: 'text'): Promise<KvCacheGetWithMetadataResult<string, Metadata>>
getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, type: 'json'): Promise<KvCacheGetWithMetadataResult<ExpectedValue, Metadata>>
getWithMetadata<Metadata = unknown>(key: Key, type: 'arrayBuffer'): Promise<KvCacheGetWithMetadataResult<ArrayBuffer, Metadata>>
getWithMetadata<Metadata = unknown>(key: Key, type: 'stream'): Promise<KvCacheGetWithMetadataResult<ReadableStream, Metadata>>

Example

Retrieve configuration with creation metadata:

// Get config with metadata information
const result = await env.demoKvCache.getWithMetadata<{version: string}>('app:config', 'json');
if (result.value) {
console.log(`Config version: ${result.value.version}`); // Access parsed value
console.log(`Created: ${result.metadata?.created}`); // Access metadata
console.log(`Cache status: ${result.cacheStatus}`); // Check cache hit/miss
}

delete

Removes a key and its associated value from storage.

delete(key: Key): Promise<void>

Example

Remove expired session data:

// Delete user session
await env.demoKvCache.delete('session:abc123');
console.log('Session removed'); // Confirm deletion