Replay Buffer
Same API as the core createReplay plugin, but backed by Redis sorted sets. Messages survive restarts and are shared across instances.
Sequence numbers are incremented atomically via a Lua script (INCR + ZADD + trim in a single EVAL), so concurrent publishes from multiple instances produce strictly ordered, gap-free sequences per topic. When the buffer exceeds size, the oldest entries are removed inside the same Lua script - no second round trip required.
When a client requests replay, the buffer checks whether the client’s last-seen sequence is older than the oldest buffered entry. If it is (the buffer was trimmed past the client’s position), a truncated event fires on __replay:{topic} before any msg events, so the client knows it missed messages and can do a full reload. This also fires when the buffer is completely empty but the sequence counter has advanced past the client’s position (e.g. all entries expired via TTL).
When to use over the built-in plugin: The core replay buffer lives in process memory - it is lost on restart and not shared between instances. Use the Redis version when you need message history that survives deploys or is consistent across a cluster.
Setup
// src/lib/server/replay.js
import { redis } from './redis.js';
import { createReplay } from 'svelte-adapter-uws-extensions/redis/replay';
export const replay = createReplay(redis, {
size: 500,
ttl: 3600 // expire after 1 hour
}); Usage
// In a form action or API route
export const actions = {
send: async ({ request, platform }) => {
const data = Object.fromEntries(await request.formData());
const msg = await db.createMessage(data);
await replay.publish(platform, 'chat', 'created', msg);
}
}; // In +page.server.js
export async function load() {
const messages = await db.getRecentMessages();
return { messages, seq: await replay.seq('chat') };
} // In hooks.ws.js - handle replay requests
export async function message(ws, { data, platform }) {
const msg = JSON.parse(Buffer.from(data).toString());
if (msg.type === 'replay') {
await replay.replay(ws, msg.topic, msg.since, platform);
return;
}
} Options
| Option | Default | Description |
|---|---|---|
size | 1000 | Max messages per topic |
ttl | 0 | Key expiry in seconds (0 = never) |
API
All methods are async (they hit Redis). The API otherwise matches the core plugin exactly:
| Method | Description |
|---|---|
publish(platform, topic, event, data) | Store + broadcast |
seq(topic) | Current sequence number |
since(topic, seq) | Messages after a sequence |
replay(ws, topic, sinceSeq, platform) | Send missed messages to one client |
clear() | Delete all replay data |
clearTopic(topic) | Delete replay data for one topic |
Was this page helpful?