Ploy
Ploy
Features

Cache

Add key-value caching to your workers with simple get/set/delete operations.

Cache

Ploy Cache provides a simple key-value store backed by Redis. Each cache entry requires a TTL (time-to-live), making it ideal for temporary data, session storage, rate limiting, and response caching.

Configuration

Add a cache binding in your ploy.yaml:

ploy.yaml
kind: dynamic
build: pnpm build
out: dist
cache:
  CACHE: default

The key (CACHE) is the binding name available in your worker's env. The value (default) is the cache identifier.

Run ploy types to generate TypeScript types:

env.d.ts
import type { CacheBinding } from "@meetploy/types";

export interface Env {
	CACHE: CacheBinding;
}

Basic Example

src/index.ts
export default {
	async fetch(request, env) {
		const url = new URL(request.url);

		if (url.pathname === "/set") {
			await env.CACHE.set("greeting", "hello world", { ttl: 3600 });
			return Response.json({ success: true });
		}

		if (url.pathname === "/get") {
			const value = await env.CACHE.get("greeting");
			return Response.json({ value });
		}

		return new Response("Cache Worker");
	},
} satisfies Ploy;

API Methods

get(key) - Get a Value

Returns the cached value or null if the key doesn't exist or has expired.

const value = await env.CACHE.get("my-key");
// value is string | null

set(key, value, opts) - Set a Value

Stores a string value with a required TTL in seconds. Overwrites any existing value for the same key.

await env.CACHE.set("session", "abc123", { ttl: 3600 }); // Expires in 1 hour

delete(key) - Delete a Value

Removes a key from the cache.

await env.CACHE.delete("session");

All cache values are strings. Use JSON.stringify() and JSON.parse() to store structured data.

Common Patterns

Storing JSON Data

// Set
const user = { name: "Alice", role: "admin" };
await env.CACHE.set("user:123", JSON.stringify(user), { ttl: 300 });

// Get
const raw = await env.CACHE.get("user:123");
const user = raw ? JSON.parse(raw) : null;

Cache-Aside Pattern

async function getUser(env: PloyEnv, userId: string) {
	const cached = await env.CACHE.get(`user:${userId}`);
	if (cached) {
		return JSON.parse(cached);
	}

	const user = await fetchUserFromDB(env, userId);
	await env.CACHE.set(`user:${userId}`, JSON.stringify(user), { ttl: 600 });
	return user;
}

Rate Limiting

async function checkRateLimit(env: PloyEnv, ip: string): Promise<boolean> {
	const key = `ratelimit:${ip}`;
	const count = await env.CACHE.get(key);

	if (count && parseInt(count) >= 100) {
		return false; // Rate limited
	}

	const newCount = count ? parseInt(count) + 1 : 1;
	await env.CACHE.set(key, String(newCount), { ttl: 60 }); // 100 req/min window
	return true;
}

Multiple Cache Bindings

You can configure multiple caches for different use cases:

ploy.yaml
cache:
  CACHE: default
  SESSION_CACHE: sessions
// General cache
await env.CACHE.set("data", value, { ttl: 3600 });

// Session-specific cache
await env.SESSION_CACHE.set("sess:abc", sessionData, { ttl: 86400 });

Next Steps

  • Databases - Add persistent SQLite databases
  • Queues - Add background job processing
  • Workers - Learn about Ploy workers

How is this guide?

Last updated on