Worlds, AI and multiplayer · 6 MIN READ

An authoritative server owns the world in one goroutine and accepts only validated intent

Build a server tick loop in which one goroutine owns all game state, clients send inputs over channels, movement is validated against speed and rate limits, and snapshots are copies in a deterministic order.

In a multiplayer game every client is a program you do not control. If clients report their own positions, a modified client can teleport, fly or walk through walls, and the server has no grounds to refuse. An authoritative server inverts that: clients send what the player wants to do, the server decides what happens, and everyone receives the server's version of the world. Goroutines and channels fit this shape well, provided exactly one goroutine owns the state.

gamedev · A MAP OF THE IDEA

  1. Stamp sender identity
  2. Drain and sort inputs
  3. Validate, then apply
  4. Publish copied snapshot

Useful when

  • A modified client cannot teleport or exceed the speed cap.
  • One owner goroutine removes locks from game logic.

Watch out

  • A blocking broadcast lets one slow client stall the tick.
  • Strict rules without tolerance punish lossy connections.

Implementation & operation cost: Server CPU for every player's simulation, a round trip of latency the client must hide, and a validation rule for every action.

01

Clients send intent; the server computes outcomes

An input message carries a sequence number and a desired direction. It has no position, health or score field, so there is nothing to forge. The server tick applies inputs with its own speed, its own collision rules from the previous unit and its own map, then publishes a snapshot. Ownership is the other half of the design: the world lives in one goroutine. Network readers and timers talk to it through channels, and nothing outside that goroutine holds a pointer into the world. That removes locks from game logic, makes each tick a sequential function you can review and test, and gives every rule a single place to be enforced. The sender's identity comes from the connection, never from a field in the payload.

02

A tick loop with validation and deterministic order

The program starts a server goroutine that owns three players, creates one Session per simulated client and runs four ticks. In each tick every client goroutine sends its inputs concurrently; the main goroutine waits for all sends, asks the server for a tick and prints the snapshot. Player 1 walks right, player 2 uses keyboard diagonals and then turns, and player 3 cheats with an oversized direction, three moves in one tick, a replayed sequence number, a NaN direction and a forged player ID.

go
package main

import (
	"cmp"
	"fmt"
	"math"
	"slices"
	"strings"
	"sync"
)

const (
	speed = 4.0   // world units per tick, decided by the server
	arena = 100.0 // the world is [0, arena] on both axes
)

// Input carries intent only. There is no position field to trust or forge.
type Input struct {
	Player int // stamped by the session, never read from the payload
	Seq    int
	DX, DY float64
}

type PlayerState struct {
	ID   int
	X, Y float64
	Ack  int // last input sequence the server has consumed
}

type Snapshot struct {
	Tick    int
	Players []PlayerState
}

type player struct {
	id, lastSeq, movedTick int
	x, y                   float64
}

// Server state is touched only by the goroutine running loop.
type Server struct {
	inputs  chan Input
	ticks   chan chan Snapshot
	players []*player
	pending []Input
	tick    int
	notes   []string
}

func NewServer(spawns map[int][2]float64, ids []int) *Server {
	s := &Server{inputs: make(chan Input), ticks: make(chan chan Snapshot)}
	for _, id := range ids {
		s.players = append(s.players, &player{id: id, x: spawns[id][0], y: spawns[id][1]})
	}
	return s
}

func (s *Server) loop(done chan<- struct{}) {
	defer close(done)
	for {
		select {
		case in := <-s.inputs:
			s.pending = append(s.pending, in)
		case reply, ok := <-s.ticks:
			if !ok {
				return
			}
			reply <- s.step()
		}
	}
}

func (s *Server) step() Snapshot {
	s.tick++
	// Arrival order depends on the scheduler; the server imposes its own.
	slices.SortFunc(s.pending, func(a, b Input) int {
		return cmp.Or(cmp.Compare(a.Player, b.Player), cmp.Compare(a.Seq, b.Seq))
	})
	for _, in := range s.pending {
		s.apply(in)
	}
	s.pending = s.pending[:0]
	snap := Snapshot{Tick: s.tick}
	for _, p := range s.players {
		snap.Players = append(snap.Players, PlayerState{ID: p.id, X: p.x, Y: p.y, Ack: p.lastSeq})
	}
	return snap
}

func (s *Server) apply(in Input) {
	i := slices.IndexFunc(s.players, func(p *player) bool { return p.id == in.Player })
	if i < 0 {
		return
	}
	p := s.players[i]
	if in.Seq <= p.lastSeq {
		s.note(in, "old or duplicate sequence dropped")
		return
	}
	p.lastSeq = in.Seq
	if p.movedTick == s.tick {
		s.note(in, "second move in one tick dropped")
		return
	}
	length := math.Hypot(in.DX, in.DY)
	if math.IsNaN(length) || math.IsInf(length, 0) {
		s.note(in, "non-finite direction rejected")
		return
	}
	dx, dy := in.DX, in.DY
	if length > 1 {
		dx, dy = dx/length, dy/length
		// A keyboard diagonal arrives as (1,1); anything longer is no real controller.
		if length > math.Sqrt2+0.001 {
			s.note(in, fmt.Sprintf("direction length %.1f clamped to 1", length))
		}
	}
	p.x = min(max(p.x+dx*speed, 0), arena)
	p.y = min(max(p.y+dy*speed, 0), arena)
	p.movedTick = s.tick
}

func (s *Server) note(in Input, msg string) {
	s.notes = append(s.notes, fmt.Sprintf("  tick %d p%d seq %d: %s", s.tick, in.Player, in.Seq, msg))
}

// Session stands in for one authenticated connection.
type Session struct {
	id  int
	out chan<- Input
}

func (c Session) Send(in Input) {
	in.Player = c.id // whatever the client wrote here is overwritten
	c.out <- in
}

func main() {
	ids := []int{1, 2, 3}
	srv := NewServer(map[int][2]float64{1: {10, 10}, 2: {50, 50}, 3: {90, 10}}, ids)
	done := make(chan struct{})
	go srv.loop(done)

	nan := math.NaN()
	script := [][][]Input{ // per tick, per player
		{{{Seq: 1, DX: 1}}, {{Seq: 1, DX: 1, DY: 1}}, {{Seq: 1, DX: 10}}},
		{{{Seq: 2, DX: 1}}, {{Seq: 2, DX: 1, DY: 1}}, {{Seq: 2, DX: 1}, {Seq: 3, DX: 1}, {Seq: 4, DX: 1}}},
		{{{Seq: 3, DX: 1}}, {{Seq: 3, DY: -1}}, {{Seq: 2, DX: 1}, {Seq: 5, DX: nan}}},
		{{{Seq: 4, DX: 1}}, {{Seq: 4, DY: -1}}, {{Seq: 6, DX: 1, Player: 1}}},
	}
	for _, perPlayer := range script {
		var wg sync.WaitGroup
		for i, inputs := range perPlayer {
			session := Session{id: ids[i], out: srv.inputs}
			wg.Go(func() {
				for _, in := range inputs {
					session.Send(in)
				}
			})
		}
		wg.Wait() // every send has been received by the server goroutine

		reply := make(chan Snapshot)
		srv.ticks <- reply
		snap := <-reply
		var parts []string
		for _, p := range snap.Players {
			parts = append(parts, fmt.Sprintf("p%d (%.1f,%.1f) ack %d", p.ID, p.X, p.Y, p.Ack))
		}
		fmt.Printf("tick %d: %s\n", snap.Tick, strings.Join(parts, " | "))
	}
	close(srv.ticks)
	<-done
	fmt.Println("violations:")
	fmt.Println(strings.Join(srv.notes, "\n"))
}
Read the code

Inputs travel over an unbuffered channel, so each Send completes only when the server goroutine has received the value, and wg.Wait therefore proves that every input is in pending before the tick request is sent. Arrival order still depends on the scheduler, so step sorts by player and sequence before applying anything, and the output is identical on every run. apply drops a sequence at or below the last one seen, allows one move per player per tick, rejects non-finite directions and normalizes any direction longer than 1, logging only lengths that no real controller produces. Dropped extras still advance the ack so the client stops resending them. Positions are clamped to the arena, which is why player 3 stops at 100.0. Session overwrites Player, so player 3's attempt to send as player 1 just moves player 3. Snapshots copy values into PlayerState, so no client can alias server memory.

03

Validation rules that do not punish honest players

Every rule needs a tolerance chosen with real networks in mind. Packets get duplicated and reordered, so an old sequence number is dropped quietly rather than treated as an attack. A burst of inputs after a lag spike is normal: a production server usually queues a few inputs per player and applies them over the next ticks, dropping only beyond that budget, whereas this program drops extras immediately to stay short. Normalizing direction vectors means a gamepad, a keyboard and a hacked client all move at the same maximum speed without the server guessing intent. Record violations with player, tick and sequence, and act on rates over time rather than on one event, because a single odd input is far more often a bug or a bad connection than a cheat. Never use a client-reported position even as a hint; if client and server disagree, the server is right and the client is corrected, which is the subject of the next lesson.

04

The production loop: a ticker, one select and non-blocking fan-out

The program drives ticks by hand to stay deterministic. A real server replaces the tick request with a time.Ticker and broadcasts each snapshot to per-client channels. The broadcast must never wait for a slow client: a full channel means that client misses this snapshot and gets the next one, which is harmless when each snapshot carries complete state rather than a delta.

go
func (s *Server) Run(ctx context.Context) {
	ticker := time.NewTicker(time.Second / 30)
	defer ticker.Stop()
	for {
		select {
		case in := <-s.inputs:
			s.pending = append(s.pending, in)
		case c := <-s.joins:
			s.clients = append(s.clients, c)
		case <-ticker.C:
			snap := s.step()
			for _, c := range s.clients {
				select {
				case c.snapshots <- snap:
				default:
					c.dropped++ // slow client: skip it, the next snapshot supersedes this one
				}
			}
		case <-ctx.Done():
			return
		}
	}
}
Read the code

This fragment runs in your own native environment; its ticks come from the wall clock, so its output is not reproducible the way the program's is. Joins arrive as messages in the same select, so the clients slice is touched only by the owner goroutine, and leaves would work the same way. Each client has a small buffered snapshots channel drained by its own writer goroutine that encodes and sends; all writers read the same snapshot, so treat it as immutable once published. A time.Ticker drops ticks when the receiver falls behind instead of queueing them, so measure each tick's duration and alert when it approaches the interval.

05

A real transport feeds the same channel

The tick loop does not care whether inputs come from an in-process Session, UDP datagrams or WebSocket messages. Fast-paced games usually prefer UDP because a lost packet should not hold newer inputs back the way in-order TCP delivery does. The reader goroutine does the untrusted-input work: size limits, decoding, mapping the sender to an authenticated session, and dropping instead of blocking when the server is busy.

go
func readInputs(conn net.PacketConn, sessions *Sessions, inputs chan<- Input) error {
	buf := make([]byte, 512)
	for {
		n, addr, err := conn.ReadFrom(buf)
		if err != nil {
			return err // closed during shutdown, or a real error
		}
		id, ok := sessions.Verify(addr, buf[:n]) // token or MAC from the handshake
		if !ok {
			continue // unknown sender: no state change and no reply
		}
		in, err := decodeInput(buf[:n]) // fixed layout, length checked
		if err != nil {
			continue
		}
		in.Player = id
		select {
		case inputs <- in:
		default:
			sessions.CountDrop(id) // server busy: drop, never stall the reader
		}
	}
}
Read the code

Run this fragment in your own environment with a conn from net.ListenPacket("udp", ":7777"); Sessions, decodeInput and the handshake are yours to define. A source address alone is not authentication, because UDP source addresses can be spoofed, so Verify checks a per-session token or message authentication code agreed during an authenticated connect. Ignoring unknown senders without replying keeps the server from becoming a traffic amplifier. The buffer is reused across reads, which is safe because decodeInput copies values into an Input before the next ReadFrom. A WebSocket transport, which needs a third-party package because the standard library has none, would feed the same channel.

06

Test the tick, not the network

Most server logic lives in step, a function of world state and a batch of inputs. Test it directly with tables of inputs and expected snapshots, including the cheats from the program, duplicated and reordered sequences, players joining and leaving between ticks, and inputs for unknown players. Run the goroutine wrapper under the race detector to prove nothing else touches the world, and fuzz decodeInput with arbitrary bytes. Then add a few integration tests over a loopback socket with injected latency and loss; they are slower and noisier, but they catch framing and shutdown bugs. This model runs in one process. A production server adds authentication, matchmaking, persistence, interest management so each client receives only nearby entities, and metrics for tick duration and per-client drops.

TAKE THIS WITH YOU

Let one goroutine own the world, accept only intent with sequence numbers, take identity from the connection, validate direction, rate and order every tick, sort inputs before applying them, and publish copied snapshots without blocking on slow clients.

Check your understanding

Why does the authoritative server accept movement directions from clients instead of positions?

Go to the source

Progress stays in this browser. No account needed.