Skip to content

TCP Protocol

Overview

The distributed cache uses a simple text-based TCP protocol, similar to Redis. Commands are sent as strings with \r\n delimiters.

Client ─── SET key value\r\n ───→ Server
Client ←── OK\r\n ────────────── Server

Commands

CommandSyntaxResponseDescription
SETSET key value [ttl]OKStore key-value pair
GETGET keyVALUE data or NULLRetrieve value
DELDEL keyOK or NULLDelete key
PINGPINGPONGHealth check
REPLICATEREPLICATE key valueOKReplicate data to node
ELECTELECT nodeIdOKLeader election

Wire Format

# Request format
COMMAND key value ttl\r\n

# Response format
STATUS data\r\n

Examples

# Store a value
SET user:123 {"name":"John","email":"john@example.com"}\r\n
→ OK\r\n

# Retrieve a value
GET user:123\r\n
→ VALUE {"name":"John","email":"john@example.com"}\r\n

# Delete a key
DEL user:123\r\n
→ OK\r\n

# Health check
PING\r\n
→ PONG\r\n

Error Handling

# Unknown command
INVALID_CMD\r\n
→ ERR Unknown command\r\n

# Key not found
GET nonexistent\r\n
→ NULL\r\n

Usage with CacheClient

typescript
import { CacheClient } from "distributed-cache";

const client = new CacheClient({
  host: "127.0.0.1",
  port: 3000,
  retryAttempts: 3,
  retryDelay: 1000,
  timeout: 5000,
});

await client.connect();

// SET
await client.set("user:123", { name: "John" });
await client.set("temp:data", "value", 5000); // with TTL

// GET
const user = await client.get("user:123");
console.log(user); // { name: "John" }

// DELETE
const deleted = await client.del("user:123");
console.log(deleted); // true

// PING
const alive = await client.ping();
console.log(alive); // true

await client.disconnect();

Client Configuration

OptionTypeDefaultDescription
hoststring"127.0.0.1"Server hostname
portnumber3000Server port
retryAttemptsnumber3Retry on failure
retryDelaynumber1000Delay between retries (ms)
timeoutnumber5000Request timeout (ms)

Released under the MIT License.