Protocol#
| Version | Date | Author | Notes |
|---|---|---|---|
| v1.0.0 | 2026-05-06 | Ben Garis-Hodge | Initial protocol documentation |
Kobolds uses a binary protocol for communication between clients and brokers. This document defines the protocol concepts, wire format, handshake flow, message serialization, authentication flow, error codes, and pattern syntax.
[!WARNING] Kobolds is pre-release software. Protocol fields, message types, transport support, authentication behavior, and compatibility guarantees may change before a stable release.
Scope#
This document describes data transmitted between Kobolds clients and brokers.
The following broker implementation details are not part of the wire protocol:
- Router and worker thread topology
- Internal broker queues
- Message pools, chunks, and reference counts
- Internal routing envelopes
- Internal connection ownership
Those details belong in the architecture document.
Terminology#
| Term | Meaning |
|---|---|
| Broker | Server that accepts connections, authenticates peers, authorizes actions and routes messages |
| Client | Application-side implementation that connects to a broker |
| Transport | Byte transport used to carry Kobolds frames, such as TCP |
| Connection | Active transport-level communication path between two peers |
| Session | Broker-side state associated with an authenticated client or peer |
| Entity | Broker-managed resource associated with a session |
| Frame | A wire-level unit containing protocol metadata and a complete or partial message |
| Message | A logical protocol operation that can span one or more frames |
| Payload | Encoded message body data |
| Pattern | A path expression used to match entity names, such as topics |
Transport#
A transport carries Kobolds protocol bytes between a client and broker. Kobolds frames are transport-independent, but transport behavior affects connection setup, ordering, reliability, and retransmission.
Supported transports#
| Transport | Status | Notes |
|---|---|---|
| TCP | Supported in protocol v1 | Reliable, ordered, bidirectional byte stream |
Planned transports#
The following transports are not part of protocol v1:
- UDP
- Shared memory
- MQTT over TCP
TCP behavior#
TCP provides ordered and reliable delivery of bytes while the connection remains active. Kobolds protocol v1 does not add message-level retransmission on top of TCP.
A successful TCP write does not by itself guarantee that the remote application has processed a message. Protocol-level acknowledgements or responses are required when an operation needs an explicit outcome.
Connections#
A connection represents an active transport-level communication path between a client and broker.
The connection is responsible for:
- Receiving bytes from the remote peer
- Parsing frames from the byte stream
- Serializing frames for outbound transmission
- Sending bytes through the active transport
- Detecting closure and transport errors
A connection is distinct from a session:
- A connection is the active transport path.
- A session is broker-managed state associated with an authenticated peer.
Sessions#
A session is broker-side state associated with an authenticated client or peer.
A session tracks the resources and metadata owned by that peer, including:
- Connection associations
- Authentication state
- Authorization context
- Session-owned entities
- Other state required to process later operations
When a session ends, the broker can use this ownership information to clean up or otherwise manage resources created by that session.
Entities#
An entity is a broker-managed object associated with a session. An entity ties a protocol-defined set of operations to the session that created it.
When an entity is created, the broker assigns an entity_id. Clients use the identifier in later actions to refer to that entity.
Entity types#
| Entity type | Supported actions |
|---|---|
| Topic | create, read, delete |
| Service | create, read, delete |
| Subscriber | create, read, delete, subscribe, unsubscribe |
| Publisher | create, read, delete |
| Requestor | create, read, delete, request |
| Replier | create, read, delete, reply |
The protocol may define additional entity types in later versions. Clients must not assume support for an entity type unless it is negotiated or documented for the connected broker version.
Serialization model#
Kobolds serializes logical messages into one or more frames. Frames are serialized into bytes and transmitted through the selected transport.
Client outbound:
message → frame or frames → bytes
Client inbound:
bytes → frame or frames → message
Broker inbound:
bytes → frame or frames → message → internal routing metadata
Broker outbound:
internal routing metadata → message → frame or frames → bytes
Only frames and their contained messages are transmitted over a transport.
Endianness and primitive encoding#
Unless a field explicitly states otherwise, all multi-byte numeric values in the Kobolds protocol use little-endian byte order.
In little-endian encoding, the least-significant byte is transmitted first. This rule applies to every fixed-width integer field in protocol frames, messages, extension headers, delivery metadata, checksums, identifiers, length fields, sequence values, and error-related fields.
| Primitive | Width | Wire encoding |
|---|---|---|
u8 |
1 byte | Single byte; endianness does not apply |
u16 |
2 bytes | Unsigned little-endian integer |
u32 |
4 bytes | Unsigned little-endian integer |
u64 |
8 bytes | Unsigned little-endian integer |
u128 |
16 bytes | Unsigned little-endian integer |
boolean |
1 bit | 0 is false, 1 is true |
| Enum | Defined by its backing integer type | Encoded using the backing type's byte order |
| Bit field | Defined field-by-field | Bit positions are specified by the relevant field definition |
| Byte slice | Variable | Preserved exactly as supplied; no byte-order conversion |
| String | Variable | Strings are currently just bytes with no real sense to them |
Receivers MUST reject a boolean field containing any value other than 0x00 or 0x01.
For example, the u32 value 0x12345678 is encoded as:
The u64 value 0x0102030405060708 is encoded as:
Byte order applies only to multi-byte numeric fields. It does not reorder:
- Raw application payload bytes
- UTF-8 string bytes
- Encoded JSON or CBOR
- Cryptographic nonces, hashes, keys, or signatures
- Explicit byte arrays and opaque binary blobs
Each payload encoding defines its own internal representation. The outer Kobolds frame and message fields still follow this section's little-endian rule unless the individual field definition explicitly states otherwise.
[!NOTE] The little-endian requirement defines the Kobolds wire format. Protocol serializers and deserializers must encode and decode multi-byte fields as little-endian values.
The current in-memory
Memoryrepresentation assumes that the host architecture uses the same byte order as the backing message representation. Consequently, the current implementation targets little-endian hosts. Big-endian host support requires explicit byte-order conversion at theMemoryboundary and is not currently guaranteed.
Frame#
A frame is a discrete wire-level unit. It contains fixed metadata, optional delivery metadata, a payload, and a checksum.
A message may fit in one frame or span multiple frames. The receiving parser uses frame metadata, including continuation state and sequence information, to reassemble the logical message.
Limits#
| Property | Protocol v1 behavior |
|---|---|
| Payload length field | Unsigned 16-bit integer |
| Maximum payload length | 65,535 bytes |
| Configurable maximum | A broker may impose a smaller configured limit |
| Checksum | xxHash32 over frame headers, optional delivery context, and payload |
| Sequence wraparound | Not defined in protocol v1 |
Frame structure#
FRAME (12+ bytes)
├─ frame_headers [8 bytes]
│ ├─ magic [2 bytes]
│ ├─ protocol_version + frame_type [1 byte]
│ │ ├─ protocol_version [4 bits]
│ │ └─ frame_type [4 bits]
│ ├─ flags [1 byte]
│ │ ├─ continuation [1 bit]
│ │ ├─ compressed [1 bit]
│ │ ├─ encrypted [1 bit]
│ │ └─ reserved [5 bits]
│ ├─ sequence [2 bytes]
│ └─ payload_length [2 bytes]
├─ delivery_context [17 bytes, optional]
│ ├─ delivery_id [8 bytes]
│ ├─ consumer_id [8 bytes]
│ └─ delivery_pattern [1 byte]
├─ payload [n bytes]
└─ checksum [4 bytes]
Frame headers#
pub const FrameHeaders = struct {
/// Resynchronization value: ASCII "KB".
magic: u16 = constants.frame_headers_magic,
/// Protocol version used to encode this frame.
protocol_version: ProtocolVersion = .v1,
/// Semantic purpose of the frame.
frame_type: FrameType = .message_raw,
/// Flags describing frame contents and reassembly behavior.
flags: FrameHeadersFlags = .{},
/// Frame sequence number.
sequence: u16 = 0,
/// Payload length in bytes.
payload_length: u16 = 0,
};
Frame representation#
pub const Frame = struct {
/// Fixed frame metadata.
frame_headers: FrameHeaders = .{},
/// Optional metadata used to route a delivery.
delivery_context: ?DeliveryContext = null,
/// A complete encoded message or part of one.
payload: []const u8,
/// xxHash32 over headers, optional delivery context, and payload.
checksum: u32 = 0,
};
[!NOTE] The
compressedandencryptedflags reserve protocol space for those behaviors. Do not assume compression or encryption is implemented merely because the flags exist.
Message#
A message is the logical protocol unit exchanged by clients and brokers. A message may represent an operation, response, event, control message, or application payload.
Messages contain:
- Fixed headers
- Optional extension headers
- Optional trace data
- A body encoded with the selected payload encoding
A message can span multiple frames when its encoded representation exceeds the maximum frame payload length.
Message structure#
MESSAGE (4+ bytes)
├─ fixed_headers [4 bytes]
│ ├─ message_type [1 byte]
│ ├─ message_body_type [1 byte]
│ ├─ encoding [1 byte]
│ └─ flags [1 byte]
│ ├─ trace [1 bit]
│ └─ reserved [7 bits]
├─ extension_headers [variable]
├─ trace [16 bytes, optional]
└─ body [variable]
In-memory representation#
The following structure is an internal Zig implementation representation. It is not transmitted directly over the wire:
pub const Message = struct {
/// Storage containing serialized and decoded message data.
memory: Memory,
/// Internal reference count for shared message ownership.
ref_count: atomic.Value(usize) = atomic.Value(usize).init(0),
};
Payloads#
A payload is the encoded body of a message. Payload encoding identifies how the sender serialized the payload and how the receiver can decode it.
Protocol-controlled payloads use known structures. Application payloads may use the unknown payload type when the broker does not need to interpret the body.
Supported encodings#
| Encoding | Description |
|---|---|
json |
JavaScript Object Notation encoding |
cbor |
Concise Binary Object Represenation encoding |
Authentication payloads#
The initial authentication payload types are:
PreSharedKeyPayload (variable)
└─ psk [n bytes]
UsernamePasswordPayload (variable)
├─ username [n bytes]
└─ password [n bytes]
Controlled payload types#
unknownusername_passwordpre_shared_keybroker_metricstopicsubscriberpublisherservicereplierrequestorentity_idpattern
Error codes#
Error codes are unsigned 8-bit values returned in applicable response messages.
| Value | Name | Meaning |
|---|---|---|
| 0 | unsupported |
No valid error code was set, or the requested operation is unsupported |
| 1 | ok |
Operation completed successfully |
| 2 | unauthenticated |
The requester is not authenticated |
| 3 | unauthorized |
The requester is authenticated but lacks permission |
| 4 | invalid_credentials |
Authentication credentials are invalid |
| 5 | invalid_topic_name |
The topic name is invalid |
| 6 | already_exists |
The requested entity already exists |
| 7 | not_found |
The requested entity was not found |
| 8 | wrong_payload_type |
The supplied payload type is invalid for the operation |
| 9 | service_unavailable |
No eligible replier is available for the requested service |
| 10 | timeout |
The operation timed out |
| 11 | unhandled_error |
An unexpected internal error occurred |
pub const ErrorCode = enum(u8) {
unsupported = 0,
ok = 1,
unauthenticated = 2,
unauthorized = 3,
invalid_credentials = 4,
invalid_topic_name = 5,
already_exists = 6,
not_found = 7,
wrong_payload_type = 8,
service_unavailable = 9,
timeout = 10,
unhandled_error = 11,
};
Authentication handshake#
A newly connected client must complete authentication before it can perform authenticated operations.
The protocol v1 authentication flow is:
Client Broker
│ │
│──── establish transport connection ──▶│
│ │
│◀──── auth_challenge ──────────────────│
│ │
│──── session_init + credentials ──────▶│
│ │
│◀──── auth_success or auth_failure ────│
│ │
Authentication challenge#
After a connection is established, the broker sends an auth_challenge.
AuthChallengeHeaders (18 bytes)
├─ supported_methods [1 byte, packed]
│ ├─ pre_shared_key [1 bit]
│ ├─ username_password [1 bit]
│ └─ reserved [6 bits]
├─ supported_algorithms [1 byte, packed]
│ ├─ none [1 bit]
│ ├─ hmac256 [1 bit]
│ └─ reserved [6 bits]
└─ nonce [16 bytes]
Protocol v1 supports the hmac256 algorithm, which refers to HMAC-SHA-256.
Session initialization#
The client responds with session_init. Its body contains an authentication payload compatible with a method and algorithm advertised by the broker.
SessionInitHeaders (11 bytes)
├─ peer_id [8 bytes]
├─ peer_type [1 byte, enum]
├─ method [1 byte, enum]
└─ algorithm [1 byte, enum]
session_join is planned and is not part of protocol v1.
Authentication result#
The broker validates the supplied credentials and returns either auth_success or auth_failure.
AuthSuccessHeaders (9 bytes)
├─ error_code [1 byte, enum]
└─ connection_id [8 bytes]
AuthFailureHeaders (1 byte)
└─ error_code [1 byte, enum]
On success, connection_id identifies the connection as assigned by the peer that sent the auth_success message.
Authentication and authorization#
Authentication establishes the identity or credential set associated with a connection. Authorization determines whether that authenticated session may perform a specific operation against a specific resource.
Kobolds uses role-based authorization. Credentials map to one or more roles; roles grant permissions over matching topics, services, key-value namespaces, and queues.
The following example is a permissive development configuration:
authorization:
roles:
- name: default
topics:
- pattern: "/**"
permissions:
- "*"
services:
- pattern: "/**"
permissions:
- "*"
kvs:
- pattern: "/**"
permissions:
- "*"
queues:
- pattern: "/**"
permissions:
- "*"
authentication:
username_passwords:
- username: default
password: "kobolds"
roles:
- default
pre_shared_keys:
- secret: kobolds
roles:
- default
[!WARNING] Do not use the example credentials in production. They grant unrestricted permissions to every configured resource pattern.
Patterns#
Patterns match entity names such as topics and services. Names are interpreted as slash-separated path segments.
Kobolds supports three pattern forms:
| Pattern form | Meaning |
|---|---|
| Literal | Matches the exact path segment text |
* |
Matches exactly one path segment |
** |
Matches zero or more path segments |
Example topic names#
/devices/thermometers/0/temperature
/devices/thermometers/0/status
/devices/thermometers/1/temperature
/devices/thermometers/1/status
/devices/motors/0/speed
/devices/motors/0/status
/devices/motors/1/speed
/devices/motors/1/status
Pattern examples#
| Pattern | Matches |
|---|---|
/devices/thermometers/0/temperature |
Only /devices/thermometers/0/temperature |
/devices/motors/0/* |
/devices/motors/0/speed, /devices/motors/0/status |
/devices/motors/*/speed |
/devices/motors/0/speed, /devices/motors/1/speed |
/devices/thermometers/** |
All descendants of /devices/thermometers |
/devices/**/status |
Every matching status path under /devices |
/** |
Every path |
/**/0/* |
Every one-segment descendant below a path segment named 0 |
Pattern-capable entities#
| Entity | Target | Status |
|---|---|---|
| Publisher | Topic | Supported |
| Subscriber | Topic | Supported |
| Requestor | Service | Planned |
| Key-value reader | Key-value entry | Planned |
| Stream reader | Stream | Planned |
| Stream writer | Stream | Planned |
Internal routing envelopes#
Routing envelopes are broker-internal metadata wrappers. They are not protocol messages and are not transmitted over a transport.
They attach ownership, destination, session, message, and optional delivery metadata while a message moves through the broker.
pub const RoutingEnvelope = struct {
/// Connection that received the message or should receive it.
connection_id: u64,
/// Optional metadata used for routed delivery.
delivery_context: ?DeliveryContext = null,
/// Internal pointer to the associated message.
message: *Message,
/// Globally unique message identifier.
message_id: u64,
/// Local identifier of the message creator.
owner_id: u64,
/// Type of entity that created the message.
owner_type: OwnerType,
/// Session associated with the connection.
session_id: ?u64 = null,
};
pub const ReclaimEnvelope = struct {
/// Internal pointer to the associated message.
message: *Message,
/// Globally unique message identifier.
message_id: u64,
/// Local identifier of the message creator.
owner_id: u64,
/// Type of entity that created the message.
owner_type: OwnerType,
};