Build and test a protocol

Write the protocol contract

Document framing, encoding, commands, replies, errors, limits, timeouts, and closure before adding features.

10 minute lesson

~~~

This final module builds a small key-value service end to end. It starts where every protocol should start: with a document, not with code.

A protocol is an agreement between independently running programs. Your server and client share an author today. They won’t forever — someone rewrites the client in Go, a monitoring script starts probing the port, a teammate builds a dashboard. The only thing keeping the endpoints compatible is the observable behavior on the wire. Write the observable contract so either endpoint can be replaced.

Create a compact contract:

encoding: UTF-8
framing: one JSON object per newline
commands: set, get, delete, quit
maximum line: 4096 bytes
idle timeout: 30 seconds
errors: structured JSON with code and message

Every line answers a question that otherwise gets answered by accident. Framing: how do I know where a message ends? Limits: how much can I send? Timeout: how long may I stay silent? Errors: what does failure look like, so I can handle it in code?

For each command, add request and reply shapes with examples:

{"type":"set","key":"color","value":"blue"}  -> {"ok":true}
{"type":"get","key":"color"}                 -> {"ok":true,"value":"blue"}
{"type":"get","key":"missing"}               -> {"ok":false,"code":"not_found"}

Examples are the most-read part of any protocol document. Make them copy-pasteable straight into nc.

Test the document, not the code

Have a second client implementation use only this document. A colleague works, and so do you next week, writing a small script while deliberately not looking at the server source. Every question the implementer must answer by reading server code is a hole in the contract. Any ambiguity it finds belongs in the contract.

Classic holes: are keys case-sensitive? Which characters can a key contain? What’s the maximum value size? What exactly happens on a line over 4096 bytes — an error reply, or an immediate close?

Do not let implementation accidents become undocumented protocol behavior. If your server happens to tolerate trailing whitespace and one client starts relying on it, that accident is now protocol you support forever. The contract decides; the code follows.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →