Introduction
gnet is a high-performance networking framework for Go that bypasses the standard net package's goroutine-per-connection model. It uses an event-driven architecture built on OS-level I/O multiplexing (epoll on Linux, kqueue on macOS/BSD) to handle massive numbers of concurrent connections with minimal resource overhead.
What gnet Does
- Handles TCP, UDP, and Unix socket connections using an event loop model
- Uses epoll/kqueue directly instead of Go's net poller for lower latency
- Supports multi-core scaling by running multiple event loops across CPU cores
- Provides a codec interface for protocol encoding and decoding
- Manages connection lifecycle through event callbacks (OnOpen, OnTraffic, OnClose)
Architecture Overview
gnet runs one or more event loops, each pinned to an OS thread. Incoming connections are distributed across loops using a load-balancing strategy (round-robin, least-connections, or source-addr hashing). Each loop polls for I/O readiness and invokes user callbacks synchronously. This reactor pattern avoids goroutine scheduling overhead and reduces memory usage to a fraction of what goroutine-per-connection designs consume.
Self-Hosting & Configuration
- Install via
go get github.com/panjf2000/gnet/v2— pure Go, no CGO - Implement the
gnet.EventHandlerinterface to define connection behavior - Call
gnet.Run()with protocol address and options - Enable multicore mode with
gnet.WithMulticore(true)to use all CPUs - Configure read buffer size, ticker interval, and load balancing strategy via options
Key Features
- Handles millions of connections with predictable low latency
- Built-in load balancing across event loops for multi-core utilization
- Ring buffer and elastic buffer implementations reduce memory allocations
- Codec interface supports custom wire protocols (length-field, delimiter, fixed-length)
- Supports both TCP and UDP in the same framework
Comparison with Similar Tools
- net/http — standard library uses goroutine-per-connection; gnet uses event loops for higher density
- Netty (Java) — similar reactor pattern; gnet brings this model to Go
- libuv (C) — cross-platform async I/O; gnet is Go-native with simpler API
- Zinx — Go TCP framework with a higher-level abstraction; gnet operates closer to the I/O layer
FAQ
Q: When should I use gnet over the standard net package? A: When you need to handle tens of thousands of concurrent connections with minimal memory, such as proxies, game servers, or IoT gateways.
Q: Does gnet work on Windows? A: Yes, gnet v2 supports Windows using a compatibility layer, though Linux and macOS offer the best performance.
Q: Can I use gnet with TLS?
A: gnet provides raw TCP. You can layer TLS on top using the crypto/tls package manually.
Q: Is gnet production-ready? A: Yes, it is used in production systems handling high-throughput workloads.