netchan
Network Channels (netchan) for Golang: Secure, cluster-ready, supports nested channels & any data type. Inspired by Rob Pike
About netchan
This large README is shown as a plain-text preview. Read the full README at the source
# Network Channels in Go — Protocol v2
[](https://pkg.go.dev/github.com/matveynator/netchan/v2)
<details>
<summary><b>🇷🇺 Русский</b></summary>
# Что такое NetChan?
Я пытаюсь донести довольно простую идею: если двум распределённым задачам нужно синхронизироваться, для этого не обязательно вводить третью сущность в виде общей базы, Redis, lock-сервиса или общей копии состояния.
Обычно мы делаем так: два процесса имеют свои состояния, а потом создаём ещё одно общее состояние где-то посередине и через него договариваемся, кто что сейчас может делать. То есть синхронизация происходит через копию или запись о реальном положении вещей.
А можно мыслить иначе: синхронизация может быть следствием самого обмена и владения ресурсом.
Представьте одно яблоко. Либо оно сейчас у меня, либо у Вас. Мы не можем одновременно есть одно и то же яблоко. Нам не нужен третий человек, который будет вести в Redis запись `apple_owner = M` и разрешать второму есть только после изменения этой записи. Сам факт передачи яблока определяет, кто им сейчас владеет.
Вот примерно такую модель я предлагаю строить через NetChan.
Не хранить отдельно общее состояние вида «кто сейчас имеет право работать», а передавать само право продолжить работу через канал. Пока сообщение, token, задача или ресурс находится у одного процесса, второго экземпляра этого права просто нет. Передал дальше — сам потерял возможность им пользоваться.
То есть вместо:
`процесс A -> Redis <- процесс B`
где Redis хранит общее состояние и оба процесса постоянно с ним сверяются,
получается:
`процесс A -> channel -> процесс B`
и сама передача через канал является изменением состояния системы.
В этом смысле мне ближе модель физического мира: один конкретный ресурс в конкретный момент находится в одном месте. Мы в программировании привыкли легко создавать копии состояния, а затем вынуждены придумывать механизмы, которые эти копии снова синхронизируют.
А можно по возможности вообще не создавать копию. Если что-то должно принадлежать строго одному участнику — передавать владение этим напрямую.
Тогда синхронизация получается не отдельным механизмом поверх системы, а свойством самой коммуникации. И именно из этой идеи выросла библиотека NetChan.
</details>
<details open>
<summary><b>🇬🇧 English</b></summary>
# What is NetChan?
What I’m trying to get people to think about is a more genuinely distributed model.
If two tasks need to synchronize, they do not necessarily need some third thing in the middle to synchronize through.
We are so used to doing this with Redis, databases, distributed locks, shared state, replicated state — some external place where we record who owns what, who is allowed to proceed, and what the current state of the world is.
But why create a second representation of reality just so that two processes can agree about the first one?
Think about a physical object. One apple.
Either I have the apple, or you have the apple.
If I give it to you, I no longer have it.
We do not need a third party maintaining a record that says:
`apple_owner = you`
The transfer of the apple is the change of state.
That is the important part.
The communication itself performs the synchronization.
This is the way I think about NetChan.
Instead of having two processes communicate indirectly through shared state:
`process A -> Redis <- process B`
they communicate directly:
`process A -> channel -> process B`
And the thing being passed through the channel can itself represent ownership, permission, work, capacity, or the right to continue.
There is no separate copy saying, “A currently owns the token.”
A has the token.
Then A sends it to B.
Now B has it.
The message transfer is not a notification about a state change.
It is the state change.
That distinction is fundamental.
In software, copying state is so cheap that we tend to copy everything first and then spend enormous effort trying to keep all those copies consistent.
In the physical world, you normally do not have this problem. A concrete thing is somewhere. If you move it, its location changes. You do not first update a database that describes where the thing is and then somehow synchronize reality with that database.
So the idea is: whenever the problem allows it, do not synchronize copies of ownership.
Do not describe ownership in shared state.
Transfer ownership.
Do not use communication to tell another process that the state has changed.
Make the communication itself be the state transition.
Then synchronization stops being a separate coordination layer built on top of the system.
Synchronization emerges naturally from the way the processes communicate. Thats why NetChan was born.
</details>
## Why NetChan
Go already has a convenient model for parallel work inside one computer: **split a large job into independent sequential tasks, run those tasks as goroutines, and connect them with channels**.
Start with an ordinary sequential computation:
```go
for i := 0; i < 1_000_000; i++ {
check(i)
}
```
This is still one sequential task. Go will not automatically split this loop across CPU cores.
To use several cores, the application first decomposes the work into independent pieces and starts those pieces as separate goroutines. Channels are then used to coordinate them:
```go
func processRange(start, end int, done chan<- struct{}) {
for i := start; i < end; i++ {
check(i)
}
done <- struct{}{}
}
func processAll() {
done := make(chan struct{})
go processRange(0, 250_000, done)
go processRange(250_000, 500_000, done)
go processRange(500_000, 750_000, done)
go processRange(750_000, 1_000_000, done)
for i := 0; i < 4; i++ {
<-done
}
}
```
Now there are four independent sequential tasks. The Go runtime can schedule those goroutines concurrently and, when several CPU cores are available, execute them in parallel.
```text
Task A -> go processRange(...) -> CPU Core 1
Task B -> go processRange(...) -> CPU Core 2
Task C -> go processRange(...) -> CPU Core 3
Task D -> go processRange(...) -> CPU Core 4
```
The roles are simple:
```text
goroutines -> independently schedulable pieces of work
channels -> communication and synchronization between them
select -> wait for several possible channel events
Go runtime -> schedules runnable goroutines on available CPU cores
```
So a channel does not make one sequential loop parallel by itself. The application decomposes the job into tasks; goroutines execute those tasks; channels connect and coordinate them.
That works very well inside one Go runtime, but a native Go `chan` does not directly cross from one computer to another.
**NetChan extends this channel model across the network.**
The goroutine itself does not move to another machine. Instead, the same task/channel worker model can continue in another process, while NetChan carries values and directional channel capabilities across the network boundary.
The important change is where a task may be executed:
```text
ordinary Go
Task A -> Machine A / Core 1
Task B -> Machine A / Core 2
Task C -> Machine A / Core 3
Task D -> Machine A / Core 4
NetChan
Task A -> Machine A / Core 1
Task B -> Machine A / Core 2
Task C -> Machine B / Core 1
Task D -> Machine B / Core 2
Task E -> Machine C / Core 1
Task F -> Machine D / Core 8
```
In short:
```text
Go:
decompose a large job into independent sequential tasks,
run them as goroutines,
coordinate them with channels,
and execute them in parallel on cores of one computer
NetChan:
extend the same channel-oriented model across the network,
so application work can also be handled by processes on other computers
```
NetChan does not make one sequential operation itself faster. It lets the same decomposition-and-channel model scale beyond one machine while keeping the programming style close to ordinary Go: goroutines, channels, `select`, and `close`.
---
## What NetChan provides
NetChan itself does **not** define a `Task`, `ManagedTask`, scheduler, request/reply protocol, or a required number of nested channels.
The library provides a more general primitive:
```text
typed Go value
+
zero or more directional channels inside that value
+
network transport
```
The root message may be any supported Go type. If that type contains directional channels, NetChan transfers those channel capabilities with the value.
For example, an application is free to define something like:
```go
type Message struct {
ID int
Payload Payload
Control <-chan Command
Result chan<- Result
Events chan<- Event
}
```
Another application may use no nested channels, one channel, two channels, or several channels, subject only to the protocol's protective limits. Their field names, message types, meaning, and lifetime belong to the application.
A nested channel may represent a reply path, cancellation, progress, events, a subscription, a long-lived session, or something completely different. NetChan transports the typed value and the channel capability; it does not assign application semantics to them.
This separation is intentional. Distributed task execution is an important use case, but it is a pattern built **on top of** NetChan rather than a restriction imposed by the library.
---
## A common task-oriented pattern
One particularly useful application pattern is a distributed worker pool. Tasks are published into a shared channel, and free workers block waiting for the next one.
```text
Task A --\
Task B ---+--> shared task channel --> Worker 1
Task C ---+ --> Worker 2
Task D --/ --> Worker 3
```
Once a worker receives a task, it executes that task's ordinary sequential code and then returns to the channel for more work.
A worker may be another goroutine on the same machine or the same worker program running on another computer. From the task's point of view, only the execution location changes:
```text
Task A -> local worker -> Machine A / Core 1
Task B -> local worker -> Machine A / Core 2
Task C -> remote worker -> Machine B / Core 1
Task D -> remote worker -> Machine C / Core 3
```
This scheduler and worker-pool behavior belongs to the application. NetChan supplies the channel transport that makes the remote workers possible.
---
## A simple task lifecycle convention
For task-oriented applications, one convenient convention is to use either a one-way task or a task with a temporary request/reply pair.
This is a **recommended application pattern, not a NetChan protocol rule**.
```text
Fire-and-Forget
Managed Task
```
### Fire-and-Forget
If the sender does not need a result or further control, the application may send only the work:
```go
type Task struct {
Work Work
}
```
```text
Task Owner ---- Work ----> Worker
```
The task is sent, executed, and forgotten. No task-local communication channels are needed.
### Managed Task
If the sender needs a result or wants to control the task while it is running, a useful convention is to include two task-scoped directional channels:
```go
type ManagedTask struct {
Work Work
Request <-chan Request
Reply chan<- Reply
}
```
The names here are from the point of view of the **task owner**, the side that creates and dispatches the task:
```text
Task Owner Worker
Work --------------------->
Request ------------------->
<---------------------- Reply
```
`Request` is owner -> worker. It may carry cancellation, parameter changes, clarification, progress requests, or other control messages.
`Reply` is worker -> owner. It may carry the final result, progress, status, partial results, or errors.
Each channel is simplex; together they form a temporary duplex session for that task.
A worker can combine ordinary sequential computation with control using normal Go `select`:
```go
for candidate := start; candidate < end; candidate++ {
select {
case request, open := <-task.Request:
if !open {
return
}
handleRequest(request)
default:
}
check(candidate)
}
```
If cancellation is all that is needed in this convention, closing the request side is enough. A receive from a closed channel becomes immediately selectable, so the worker can stop and return to the pool.
For this pattern, keeping the shape simple is useful:
```text
Fire-and-Forget:
Work
Managed Task:
Work + Request + Reply
```
But NetChan does not enforce that shape. An application may define a different task type with one control channel, several result channels, event streams, separate cancellation and progress channels, or any other arrangement supported by the protocol.
When an application chooses the `Request` / `Reply` convention, the pair is naturally task-scoped: a task gets a fresh pair, that pair ends with the task, and the next task gets different channels.
```text
Task A
├── Request A
└── Reply A
Task A ends
Task B
├── Request B
└── Reply B
```
The same pair is not reused for another logical task.
---
## Competitive execution
A scheduler does not have to assign exactly one worker to every logical task.
If there are many idle workers, several of them may execute copies of the same important task:
```text
Task A -> Worker 01
Task A -> Worker 02
Task A -> Worker 03
...
```
If the application uses the `Request` / `Reply` convention, the first valid reply can win:
```text
Worker 01 -------\
Worker 02 --------\
Worker 03 ---------> first valid Reply wins
Worker 04 --------/
Worker 05 -------/
```
The task owner can then stop the remaining copies through the request/control path. The losing workers return to the common pool and can immediately take other work.
This is an application-level form of distributed speculative execution.
---
## Decomposition instead of competition
Competition is only one scheduling strategy. Often the better approach is to split a large search or computation into many smaller independent tasks:
```text
0 ------------------------------------------------------ 100,000,000
```
becomes:
```text
Task 1: 0 - 999,999
Task 2: 1,000,000 - 1,999,999
Task 3: 2,000,000 - 2,999,999
Task 4: 3,000,000 - 3,999,999
...
```
and workers consume them as they become free:
```text
Task 1 -> Machine A / Core 1
Task 2 -> Machine A / Core 2
Task 3 -> Machine B / Core 1
Task 4 -> Machine B / Core 2
Task 5 -> Machine C / Core 1
```
Each task remains ordinary sequential code. Fast workers naturally complete more tasks; slow workers complete fewer.
---
## Heterogeneous workers
A distributed pool does not need identical hardware. It may contain old laptops, desktop CPUs, large servers, ARM machines, cloud VMs, GPUs, storage-heavy nodes, or specialized accelerators.
Workers can keep application-level performance statistics such as:
```text
operations / second
iterations / second
average task runtime
factoring speed
encoding speed
rendering speed
```
A scheduler can use those measurements to decide where a task should run or how large a task should be:
```text
Task target: < 500 ms
Worker A estimate: 8.2 s -> unsuitable
Worker B estimate: 190 ms -> execute
```
NetChan provides the communication model; scheduling policy belongs to the application.
---
## Example workloads
The worker-pool pattern is useful whenever a larger problem can be decomposed into independent work, for example:
- factoring and mining-style workloads;
- large search spaces;
- rendering;
- video and media processing;
- compression;
- scientific simulations and Monte Carlo workloads;
- crawling and indexing;
- distributed builds;
- testing and fuzzing;
- batch data processing;
- independent AI inference jobs.
These are examples, not limits on what NetChan can transport. Applications may use nested network channels for many other communication patterns as well.
---
## The idea in one picture
```text
one sequential computation
|
v
decompose into independent tasks
|
+--> Task A
+--> Task B
+--> Task C
+--> Task D
|
v
Go goroutines + chan
|
v
cores of one machine
|
v
NetChan
|
v
other processes and machines
|
v
distributed worker pool
```
A common task convention is:
```text
Fire-and-Forget: Work
Managed Task: Work + Request + Reply
```
But the NetChan primitive itself remains more general:
```text
supported typed value
+
zero or more nested directional channels
```
---
## How NetChan works
Go channels are simple not merely because they carry values. They connect
independent processes, synchronize them, and transfer responsibility for data.
After a successful send, a value logically disappears from the sender and
appears at the receiver. This property is what “quantum” refers to here.
NetChan extends the same model across processes and computers:
```go
connection.Send <- message
message = <-connection.Receive
```
In protocol v2, a network channel can carry ordinary supported values and
directional channels inside those values. NetChan does not interpret the nested
channels as requests, replies, cancellation, or sessions; those meanings belong
to the application.
It preserves message order, provides backpressure, recovers from temporary
disconnections, and distinguishes receipt by the remote node from an actual read
by the remote goroutine.
A distributed task system is one common application. Such an application may use
no nested channels for one-way work, or a temporary `Request` / `Reply` pair for
control and results. Another application may choose a completely different set of
nested channels.
NetChan still does not hide the physics of a distributed system: the network
requires encoding and a temporary copy, while two independent Go schedulers
cannot perform a single atomic cross-machine `select`. These boundaries are
represented by explicit channels and protocol states rather than message loss or
hidden shared state.
> **Project status:** v2 is the current major version. New releases follow SemVer,
> pass mandatory security checks, and enter `main` only through pull requests.
## Why “Quantum” Network Channels
Within a single process, the Go runtime acts as a channel hypervisor: it knows
which goroutine is sending a value, which one is ready to read it, and when the
right to continue is transferred.
There is no shared runtime between computers. In NetChan v2, a logical session
and the acknowledgement protocol act as the network hypervisor:
1. the sender transfers a value to the local NetChan actor;
2. the value is encoded and registered on the remote side;
3. the remote application reads it from an ordinary Go channel;
4. the read acknowledgement returns to the sender;
5. the temporary encoded copy is released.
On the wire, this transition is represented by:
```text
DATA → PREPARED → DELIVERED → RELEASE
```
Here, “disappearance” means a transfer of logical ownership. After sending, the
sender no longer modifies the transferred maps, slices, or pointer-referenced
data; the receiver becomes the new owner after reading. The network needs a
physical copy for disconnection recovery, and it exists only until acknowledgement.
## What changed since the first version
| Protocol v1 limitation | Protocol v2 implementation |
|---|---|
| Sending was not synchronized with the remote read | `Deliver` completes only after the remote application reads the value |
| A network error could lose a message | Unacknowledged-message journal, ACKs, replay, and deduplication |
| Primarily values could be transferred | Messages can carry directional nested channels |Frequently Asked Questions
What is netchan?
netchan is a Networking library for the Go programming language. Network Channels (netchan) for Golang: Secure, cluster-ready, supports nested channels & any data type. Inspired by Rob Pike
How do I install netchan?
Install netchan with the Go module system using `go get matveynator/netchan`. Check the repository for the current installation instructions.
What category does netchan belong to?
netchan is listed under Networking, specifically Networking.