← Complete Projects

阅读中文版本

Build a TCP Key-Value Store Server and Client

A line-oriented TCP server that stores keys in memory with optional persistence, supports GET, SET, DEL, and KEYS commands, and ships a client that speaks the same protocol.

intermediate~5 hnodejstcpnetworkingserver

Project goal

Build a TCP server that accepts line-based commands over a socket, implements GET, SET, DEL, and KEYS against an in-memory map, snapshots to disk, and provide a client for the same protocol.

Final features

  • Accept concurrent TCP connections and read one command per line.
  • Implement GET, SET, DEL, KEYS, and QUIT with clear replies.
  • Persist the map to a snapshot file and reload it on start.
  • Return protocol errors for malformed commands without dropping the connection.
  • Provide a client that sends a command and prints the reply.

Architecture

A protocol module parses a line into a command and renders a reply; a store module owns the map and optional snapshot; a connection handler loops over lines using a buffered reader for partial packets; and the client reuses the protocol module to stay in sync with the server.

Prerequisites

  • Node.js 20 LTS or later
  • Understanding of TCP sockets and streaming data
  • Basic knowledge of line-delimited protocols

Dependencies

  • node >=20 — node:net for the TCP server and client
  • vitest ^2.1.0 — Protocol and store tests, plus a socket round-trip

Directory structure

kv-store/
├── src/
│   ├── protocol.js
│   ├── store.js
│   ├── server.js
│   └── client.js
├── test/
│   ├── protocol.test.js
│   └── socket.test.js
└── package.json

Phases

1. Store with snapshots

Implement an in-memory map with optional snapshot load and save and a keys listing.

Files: src/store.js

import { readFileSync, writeFileSync } from 'node:fs';

export function createStore(snapshotPath) {
  let data = new Map();
  if (snapshotPath) {
    try { data = new Map(Object.entries(JSON.parse(readFileSync(snapshotPath, 'utf8')))); }
    catch { data = new Map(); }
  }
  return {
    get: (k) => data.get(k),
    set: (k, v) => { data.set(k, v); },
    del: (k) => data.delete(k),
    keys: () => [...data.keys()],
    snapshot() {
      if (snapshotPath) writeFileSync(snapshotPath, JSON.stringify(Object.fromEntries(data)));
    },
  };
}

Expected behavior: Setting then getting returns the value, deleting reports true once and false after, and a snapshot reloads the same map.

2. Protocol parsing

Split a command line into a verb and arguments and render a reply string for every case.

Files: src/protocol.js

function splitArgs(line) {
  return line.trim().split(/\s+/);
}

export function execute(store, line) {
  const [verb, key, ...rest] = splitArgs(line);
  switch ((verb ?? '').toUpperCase()) {
    case 'GET': {
      const value = store.get(key);
      return value === undefined ? '(nil)' : value;
    }
    case 'SET':
      store.set(key, rest.join(' '));
      return 'OK';
    case 'DEL':
      return store.del(key) ? '1' : '0';
    case 'KEYS':
      return store.keys().join(' ');
    case 'QUIT':
      return 'BYE';
    default:
      return 'ERR unknown command';
  }
}

Expected behavior: A SET stores a value with spaces in it, a GET of a missing key returns the nil marker, and an unknown verb returns ERR without throwing.

3. Line-buffered connection handling

Read a socket with a buffer that survives partial packets and process one command per newline.

Files: src/connection.js

import { execute } from './protocol.js';

export function handleConnection(socket, store) {
  let buffer = '';
  socket.on('data', (chunk) => {
    buffer += chunk.toString('utf8');
    let index;
    while ((index = buffer.indexOf('\n')) >= 0) {
      const line = buffer.slice(0, index);
      buffer = buffer.slice(index + 1);
      const reply = execute(store, line);
      socket.write(reply + '\n');
      if (reply === 'BYE') socket.end();
    }
  });
  socket.on('error', () => socket.destroy());
}

Expected behavior: A command split across two data events is processed once, and two commands in one chunk produce two replies in order.

4. Snapshot on write

Persist the store after mutating commands and on shutdown so a clean restart resumes state.

Files: src/persistence.js

export function withSnapshot(store, { everyWrites = 10 } = {}) {
  let writes = 0;
  return {
    ...store,
    set(key, value) { store.set(key, value); if (++writes % everyWrites === 0) store.snapshot(); },
    del(key) { const ok = store.del(key); store.snapshot(); return ok; },
  };
}

Expected behavior: A periodic snapshot runs after the configured number of writes, and a delete snapshots immediately so it survives a crash.

5. Server and client

Start the TCP server on a configurable port and provide a client that sends one command and prints the reply.

Files: src/server.js, src/client.js

import { createServer } from 'node:net';
import { createStore } from './store.js';
import { handleConnection } from './connection.js';

const store = createStore(process.env.SNAPSHOT ?? './kv.snapshot');
const server = createServer((socket) => handleConnection(socket, store));
server.listen(process.env.PORT ?? 6379, () => console.log('kv listening on ' + (process.env.PORT ?? 6379)));
export { server };

Expected behavior: The server logs a listening line on start, and a client sending SET then GET over a socket receives OK then the stored value.

6. Socket round-trip tests

Start the server on an ephemeral port, connect a client, and assert the reply stream for a command sequence.

Files: test/socket.test.js

import { createServer } from 'node:net';
import { connect } from 'node:net';
import { createStore } from '../src/store.js';
import { handleConnection } from '../src/connection.js';

test('set then get over a real socket', async () => {
  const store = createStore();
  const server = createServer((s) => handleConnection(s, store));
  await new Promise((r) => server.listen(0, r));
  const client = connect(server.address().port);
  const replies = [];
  client.on('data', (d) => replies.push(...d.toString().trim().split('\n')));
  client.write('SET greeting hello\n');
  client.write('GET greeting\n');
  await new Promise((r) => setTimeout(r, 50));
  expect(replies).toEqual(['OK', 'hello']);
  client.end();
  server.close();
});

Expected behavior: The socket test passes with the server on an OS-assigned port, and the two replies arrive in the order the commands were sent.

Testing

Run npx vitest. Protocol tests assert every command and the error reply, including a SET of an empty value. Store tests cover overwrite, delete, and snapshot round-trip. A socket test starts the server on an ephemeral port, sends a SET then a GET through a real client, and asserts the reply.

Troubleshooting

A command sent in two packets parses as two broken commands

Buffer incoming data and only process complete lines, keeping the trailing partial bytes for the next event; assuming one data event equals one command is the classic framing bug.

The server hangs on shutdown

Call socket.end on QUIT and close the listener on shutdown; leaving sockets open keeps the event loop alive and the process never exits.

A value containing spaces is truncated

Split the verb and key from the line first, then take the remainder as the value; re-splitting the whole line on whitespace loses the spaces inside the value.

Deployment

Bind the server behind a private network and expose only to trusted clients, since the protocol has no authentication. The snapshot file on a mounted volume gives restart durability; a production version would add auth and a write-ahead log.

Known limitations

  • Data lives in memory and is snapshotted, not written per operation, so a hard crash can lose recent writes.
  • There is no authentication or access control; anyone who can reach the port can read and write every key.

Project overview

A key-value server on a raw TCP socket is the shortest path to understanding network programming: framing, partial reads, concurrent connections, and a protocol that both ends share.

The store keeps data in memory and snapshots to disk, so a restart resumes state. Every command is parsed and rendered by one shared protocol module, which is what keeps client and server honest.

The protocol is a pure function over a line, which makes both ends testable without opening a socket:

export function execute(store, line) {
  const [verb, key, ...rest] = splitArgs(line);
  switch ((verb ?? '').toUpperCase()) {
    case 'GET': {
      const value = store.get(key);
      return value === undefined ? '(nil)' : value;
    }
    case 'SET':
      store.set(key, rest.join(' '));
      return 'OK';
    case 'DEL':
      return store.del(key) ? '1' : '0';
    case 'KEYS':
      return store.keys().join(' ');
    case 'QUIT':
      return 'BYE';
    default:
      return 'ERR unknown command';
  }
}

Splitting parsing from transport means the same function answers a socket command in production and a test assertion in the suite.

Setup

No dependencies beyond the test runner; node:net provides both the listening socket and the connecting client.

Dependency Version Why it is here
node >=20 node:net for the TCP server and client
vitest ^2.1.0 Protocol and store tests, plus a socket round-trip

Create the project and install:

mkdir kv-store && cd kv-store
npm init -y
npm install -D vitest@^2.1.0

Configure the server and client entries plus the test runner:

{
  "name": "kv-store",
  "type": "module",
  "scripts": {
    "server": "node src/server.js",
    "client": "node src/client.js",
    "test": "vitest run"
  }
}

Tests bind the server to port 0 so the operating system picks a free port and parallel test runs never collide.

Phase 1: Store with snapshots

Implement an in-memory map with optional snapshot load and save and a keys listing. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.

import { readFileSync, writeFileSync } from 'node:fs';

export function createStore(snapshotPath) {
  let data = new Map();
  if (snapshotPath) {
    try { data = new Map(Object.entries(JSON.parse(readFileSync(snapshotPath, 'utf8')))); }
    catch { data = new Map(); }
  }
  return {
    get: (k) => data.get(k),
    set: (k, v) => { data.set(k, v); },
    del: (k) => data.delete(k),
    keys: () => [...data.keys()],
    snapshot() {
      if (snapshotPath) writeFileSync(snapshotPath, JSON.stringify(Object.fromEntries(data)));
    },
  };
}

Acceptance for this phase: Setting then getting returns the value, deleting reports true once and false after, and a snapshot reloads the same map.

Phase 2: Protocol parsing

Split a command line into a verb and arguments and render a reply string for every case. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.

function splitArgs(line) {
  return line.trim().split(/\s+/);
}

export function execute(store, line) {
  const [verb, key, ...rest] = splitArgs(line);
  switch ((verb ?? '').toUpperCase()) {
    case 'GET': {
      const value = store.get(key);
      return value === undefined ? '(nil)' : value;
    }
    case 'SET':
      store.set(key, rest.join(' '));
      return 'OK';
    case 'DEL':
      return store.del(key) ? '1' : '0';
    case 'KEYS':
      return store.keys().join(' ');
    case 'QUIT':
      return 'BYE';
    default:
      return 'ERR unknown command';
  }
}

Acceptance for this phase: A SET stores a value with spaces in it, a GET of a missing key returns the nil marker, and an unknown verb returns ERR without throwing.

Phase 3: Line-buffered connection handling

Read a socket with a buffer that survives partial packets and process one command per newline. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.

import { execute } from './protocol.js';

export function handleConnection(socket, store) {
  let buffer = '';
  socket.on('data', (chunk) => {
    buffer += chunk.toString('utf8');
    let index;
    while ((index = buffer.indexOf('\n')) >= 0) {
      const line = buffer.slice(0, index);
      buffer = buffer.slice(index + 1);
      const reply = execute(store, line);
      socket.write(reply + '\n');
      if (reply === 'BYE') socket.end();
    }
  });
  socket.on('error', () => socket.destroy());
}

Acceptance for this phase: A command split across two data events is processed once, and two commands in one chunk produce two replies in order.

Phase 4: Snapshot on write

Persist the store after mutating commands and on shutdown so a clean restart resumes state. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.

export function withSnapshot(store, { everyWrites = 10 } = {}) {
  let writes = 0;
  return {
    ...store,
    set(key, value) { store.set(key, value); if (++writes % everyWrites === 0) store.snapshot(); },
    del(key) { const ok = store.del(key); store.snapshot(); return ok; },
  };
}

Acceptance for this phase: A periodic snapshot runs after the configured number of writes, and a delete snapshots immediately so it survives a crash.

Phase 5: Server and client

Start the TCP server on a configurable port and provide a client that sends one command and prints the reply. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.

import { createServer } from 'node:net';
import { createStore } from './store.js';
import { handleConnection } from './connection.js';

const store = createStore(process.env.SNAPSHOT ?? './kv.snapshot');
const server = createServer((socket) => handleConnection(socket, store));
server.listen(process.env.PORT ?? 6379, () => console.log('kv listening on ' + (process.env.PORT ?? 6379)));
export { server };

Acceptance for this phase: The server logs a listening line on start, and a client sending SET then GET over a socket receives OK then the stored value.

Phase 6: Socket round-trip tests

Start the server on an ephemeral port, connect a client, and assert the reply stream for a command sequence. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.

import { createServer } from 'node:net';
import { connect } from 'node:net';
import { createStore } from '../src/store.js';
import { handleConnection } from '../src/connection.js';

test('set then get over a real socket', async () => {
  const store = createStore();
  const server = createServer((s) => handleConnection(s, store));
  await new Promise((r) => server.listen(0, r));
  const client = connect(server.address().port);
  const replies = [];
  client.on('data', (d) => replies.push(...d.toString().trim().split('\n')));
  client.write('SET greeting hello\n');
  client.write('GET greeting\n');
  await new Promise((r) => setTimeout(r, 50));
  expect(replies).toEqual(['OK', 'hello']);
  client.end();
  server.close();
});

Acceptance for this phase: The socket test passes with the server on an OS-assigned port, and the two replies arrive in the order the commands were sent.

Testing strategy

Run npx vitest. Protocol tests assert every command and the error reply, including a SET of an empty value. Store tests cover overwrite, delete, and snapshot round-trip. A socket test starts the server on an ephemeral port, sends a SET then a GET through a real client, and asserts the reply.

The framing test delivers a command in two chunks and asserts the server still parses it, which is the partial-read bug that naive socket servers hit first.

Extending the project

Expiry, atomic counters, and pub-sub are additional verbs over the same store. A snapshot interval or write-ahead log upgrades durability, and a binary framing is a drop-in replacement for the line reader because the command handling sits behind the protocol module.