Software Engineering
Build multiplayer game servers: TCP/UDP and sockets, concurrency models, databases, messaging and cloud hosting.
A path for engineers who build the servers behind online games. It starts with how TCP, UDP and IP really behave, moves through sockets, serialization, threads and synchronization, then covers concurrency architectures (reactor, proactor, actors, reactive), databases, messaging, containers, cloud hosting and server-side ML. Each subject links the official documentation, RFCs or well-known references.
The subjects follow the roadmap.sh Server Side Game Developer roadmap.
A game server is the authority that owns the simulation: it receives player input, advances the world, validates every action and streams state back to clients. Around it sit the services a live game needs — login, matchmaking, persistence, leaderboards and telemetry. The work is networking, concurrency and operations far more than rendering.
The connection-oriented transport that turns lossy packets into an ordered, reliable byte stream. It is the default for login, chat, matchmaking and turn-based games, but head-of-line blocking makes it a poor fit for fast real-time state. Learn the header, the handshake and the options negotiated at connect time.
Each segment starts with a 20-byte fixed header (up to 60 with options): ports, 32-bit sequence and ack numbers, a data offset, control bits such as SYN and RST, the advertised window, a checksum and an urgent pointer.
Both TCP and UDP use a 16-bit ones-complement sum over a pseudo-header, the transport header and the payload. It catches simple corruption but is weak, so anything security-sensitive relies on TLS or an application MAC instead.
A client sends SYN, the server answers SYN-ACK, the client confirms with ACK; each side later sends its own FIN, and whoever closed first lingers in TIME_WAIT. Reading ss -tan against the state diagram explains stuck sockets and port exhaustion.
Every open connection costs a file descriptor, kernel send and receive buffers and per-socket state. Servers with many players raise ulimit -n, size buffers deliberately and reap idle or half-open connections with timeouts and keepalives.
The MSS option advertises the largest payload a host will accept in one segment, normally the path MTU minus IP and TCP headers (1460 bytes on standard Ethernet with IPv4). Getting it wrong leads to fragmentation or black-holed packets.
How the effective segment size adapts to the path: MSS clamping on routers and Path MTU Discovery lower it when a link along the route has a smaller MTU, avoiding IP fragmentation.
The 16-bit window field caps unacknowledged data at 64 KB. The window scale option, agreed in the handshake, shifts it left by up to 14 bits so high-bandwidth, high-latency links can stay full.
The timestamp option echoes a sender clock value back in ACKs, giving accurate round-trip measurements and protecting against wrapped sequence numbers (PAWS) on fast links.
How TCP actually moves bytes once a connection is up: segmenting the stream, acknowledging it, retransmitting what is lost and pacing the sender so neither the receiver nor the network is overwhelmed. These mechanisms are also the blueprint for any reliable layer you build over UDP.
Every byte has a sequence number; the receiver acknowledges cumulatively and the sender retransmits on timeout or after three duplicate ACKs. The retransmission timer is derived from smoothed RTT measurements.
Corrupted segments fail the checksum and are silently dropped, which the sender then sees as loss. Duplicates and out-of-order segments are detected through sequence numbers and reassembled before data reaches the application.
The receiver advertises how much buffer space it has left, and the sender never has more unacknowledged data in flight than that window. A slow reader therefore throttles the sender instead of losing data.
Slow start, congestion avoidance and fast recovery shrink the sending rate when loss or delay signals a congested path; modern stacks use CUBIC or BBR. UDP has none, so a game protocol must add its own rate limiting.
SACK lets the receiver report exactly which blocks arrived after a gap, so the sender retransmits only the missing pieces rather than everything after the first loss.
The URG flag and urgent pointer were meant to send data ahead of the stream, read with MSG_OOB. Implementations disagree on the semantics and new protocols should not use it; send a separate message or connection instead.
TCP was designed for a cooperative network, and several attacks abuse its state machine. Game servers are frequent DDoS targets, so you need to know how the classic attacks work and which kernel settings and infrastructure blunt them.
SYN floods fill the half-open connection queue with spoofed handshakes; SYN cookies (net.ipv4.tcp_syncookies) answer without storing state. Volumetric floods need upstream scrubbing or a provider with DDoS protection.
An attacker who can guess or observe sequence numbers can inject data into an established session. Randomised initial sequence numbers make blind attacks hard; encryption with TLS makes injected bytes useless.
Forging a RST (or SYN) with an acceptable sequence number tears down someone else's connection, effectively vetoing it. Stacks now require an exact sequence match and send challenge ACKs before accepting a reset.
A thin, connectionless transport: each sendto becomes one datagram with no handshake, ordering or retransmission. Real-time games use it because a late position update is worthless anyway, then build exactly the reliability they need on top. QUIC shows the same idea done generically.
Eight bytes of header — source port, destination port, length and checksum — followed by the payload. Keep game packets under roughly 1200 bytes to stay below common path MTUs and avoid fragmentation.
A self-contained message delivered whole or not at all; message boundaries are preserved, unlike TCP's stream. Datagrams may be lost, duplicated or reordered, and the receiver gets no notification of any of it.
Neither IP nor UDP guarantees delivery, so games add sequence numbers, ack bitfields piggybacked on every packet and selective resend for messages that must arrive, while unreliable state snapshots simply get superseded.
Choosing the transport is a per-message decision more than a per-game one: many games run a TCP or WebSocket channel for lobby and chat and UDP for the simulation. The trade-offs come down to latency versus guarantees.
TCP retransmits until data arrives or the connection dies; UDP fires and forgets. For a 60 Hz state stream, waiting on a resend is worse than using the next update.
TCP delivers bytes strictly in order, so one lost segment stalls everything behind it (head-of-line blocking). UDP hands datagrams up as they arrive and lets the game discard stale ones by sequence number.
TCP carries a 20–60 byte header plus handshake, per-connection kernel state and timers; UDP adds 8 bytes and no state. That difference matters at tens of thousands of players.
TCP exposes a byte stream, so the application must frame its own messages with length prefixes. UDP exposes discrete datagrams whose boundaries survive the trip.
TCP is strictly one-to-one. UDP can also be sent to a broadcast or multicast address, which LAN games use for server discovery but which rarely crosses the public internet.
The Internet Protocol moves individual packets from host to host across many networks on a best-effort basis. Everything above it — TCP, UDP, QUIC — inherits its addressing, its MTU limits and its lack of guarantees.
IP does two jobs: give every interface an address and forward each packet hop by hop toward its destination, fragmenting it when a link's MTU is too small.
What IP offers and what it leaves out: addressing, routing, fragmentation, TTL to kill loops and a header checksum (IPv4 only) — but no delivery, ordering or congestion guarantees.
Each link has a maximum bit rate and an MTU. Throughput is capped by the slowest hop, and once queues fill packets get delayed or dropped, which players experience as lag spikes and loss.
Building an IP packet: version, header length, TTL, protocol number, source and destination addresses and checksum, then the transport payload. Raw sockets (SOCK_RAW) let you craft these by hand for tools and tests.
Routers forward each packet using the longest-prefix match in their table; BGP stitches autonomous systems together. Route choice drives latency, which is why game hosts pick regions and peering carefully.
How hosts are named and found: address families and their notation, address classes and CIDR blocks, and the helper protocols that map names to addresses and addresses to hardware. Server code meets all of it when it binds, connects and resolves.
Addresses fall into unicast, multicast, broadcast and anycast, and into public versus private ranges (10/8, 172.16/12, 192.168/16). The old class A/B/C split was replaced by CIDR prefixes.
32-bit addresses written as dotted quads. Exhaustion led to NAT everywhere, which is why peer-to-peer games need NAT traversal and dedicated servers are easier to reach.
128-bit addresses, a simpler fixed header, no router fragmentation and no need for NAT. Mobile networks are often IPv6-first, so servers should listen dual-stack.
Resolves an IPv4 address to a MAC address on the local network by broadcasting a request and caching the reply. IPv6 does the same job with Neighbor Discovery.
Hands out IP addresses, gateways and DNS servers to hosts as they join a network, using leases that must be renewed.
The distributed name system that turns play.example.com into addresses via A and AAAA records. Short TTLs enable fast failover; SRV records can advertise service ports. Resolve with getaddrinfo, never hard-code IPs.
Game servers are written in whatever gives the team control over latency and memory while keeping development fast. C++ and C# dominate where the server shares code with the engine; Java, Go and Erlang are common for backend services and highly concurrent session servers.
Maximum control over memory layout and threads, and the language of Unreal and most custom engines. Pay for it with manual lifetime management; use RAII, sanitizers and modern standard library types.
The Unity language and a strong server choice on .NET, with async/await, Span<T> for low-allocation parsing and a fast cross-platform runtime.
A mature JVM ecosystem with Netty for networking, java.util.concurrent and virtual threads (Java 21) for cheap concurrency. Watch garbage collection pauses on latency-critical loops.
Built for telecom switches: millions of isolated lightweight processes, message passing and supervision trees that restart failed parts. Used for chat and presence services in large online games.
Simple syntax, fast compiles, goroutines and channels in the language, and a single static binary to deploy. Popular for matchmaking, lobby and backend services.
With Node.js the same language runs in the browser client and on the server, which suits web and casual games. Its single-threaded event loop is easy to reason about but CPU-heavy simulation needs worker threads.
Sockets are the operating system's interface to the network stack. Even if you use a library like ENet, Netty or ASIO, knowing the raw calls, their blocking behaviour and their error codes is what lets you debug production networking.
The original Unix socket API that every platform copied. Servers call socket, bind, listen and accept; clients call connect; UDP code uses sendto and recvfrom.
Windows' socket implementation: BSD-like calls plus WSAStartup, SOCKET handles instead of ints, closesocket and WSAGetLastError, and Windows-only extensions such as overlapped I/O.
On Unix a socket is a file descriptor, an integer index into the process's open-file table, so it works with read, write, close and fcntl(fd, F_SETFL, O_NONBLOCK). Leaked descriptors eventually hit the per-process limit.
The calls and options you use daily: setsockopt for SO_REUSEADDR, TCP_NODELAY and buffer sizes, shutdown for half-close, and handling EAGAIN, EINTR and partial sends.
Network byte order is big-endian, so integers go through htons/htonl and back with ntohs/ntohl. Bit-packing values into fewer bytes is a standard trick to shrink game packets.
inet_pton and inet_ntop convert between text and binary addresses for both IPv4 and IPv6; getaddrinfo resolves names into ready-to-use sockaddr structures. Avoid the IPv4-only inet_addr.
Turning in-memory game state into bytes for the wire or disk and back again. Text formats are easy to debug and suit configuration and web APIs; binary formats are what you send sixty times a second. Always validate input — the client is not trusted.
The default for HTTP APIs and tooling: human-readable and universally supported, but verbose and slow to parse compared with binary formats. Numbers are doubles in many parsers, so send large IDs as strings.
A verbose, schema-able markup format still found in older services and configuration. Disable external entity resolution when parsing untrusted XML to avoid XXE attacks.
Indentation-based configuration format used by Kubernetes, Docker Compose and CI systems. Watch implicit typing gotchas such as no becoming a boolean in older parsers.
A small, explicit configuration format with clear types and sections, common in Rust and Python tooling and easy to read for server config files.
Google's schema-first binary format: define messages in .proto files, generate code for each language, and evolve fields safely by number. Compact, fast and the payload format of gRPC.
A game server must assume every client is hostile: encrypt traffic, authenticate sessions, validate every action server-side and rate-limit everything. Transport encryption is the floor, not the whole job.
Encrypts and authenticates TCP connections with certificates; TLS 1.3 cuts the handshake to one round trip. For UDP, DTLS or QUIC provide the equivalent.
TLS's predecessor. All SSL versions are broken (POODLE and friends) and prohibited; the name survives only in library names like OpenSSL and in casual usage.
An encryption algorithm. Use authenticated modes such as AES-GCM or ChaCha20-Poly1305 from a vetted library, never a home-made scheme, and pick TLS cipher suites from current guidance.
Using several threads in one process to keep all cores busy with networking, simulation, persistence and AI. Shared mutable state is the hazard: every thread-safety bug is a race on data someone forgot to protect, so design ownership before you add locks.
Variables with one copy per thread, declared with thread_local in C++ or ThreadLocal in Java. Handy for per-thread allocators, random generators and scratch buffers without locking.
The POSIX threads API on Linux and macOS: pthread_create, pthread_join, mutexes, condition variables and pthread_key_create for thread-specific data.
Win32 threading: CreateThread, TlsAlloc/TlsGetValue for dynamic thread-local slots, __declspec(thread) for static ones, plus slim reader/writer locks and thread pools.
A user-mode execution context scheduled cooperatively by your code rather than the OS. Fibers switch far more cheaply than threads; job systems use them to suspend a job mid-way without blocking a worker thread.
The primitives that coordinate threads: who may touch shared data, who waits for whom, and how results are handed over. Choose the simplest one that is correct, keep critical sections short and always acquire locks in a fixed order to avoid deadlock.
Mutual exclusion: only the thread holding the lock enters the critical section. In C++ pair std::mutex with std::scoped_lock so it is released on every path, including exceptions.
A lock that busy-waits instead of sleeping. Only worth it when the hold time is a few instructions and threads run on separate cores; otherwise it burns CPU and can starve the holder.
A counter that limits how many threads may proceed at once — useful for bounding concurrent database connections or jobs. A binary semaphore behaves like a lock without ownership.
Lets a thread sleep until another signals that some state changed. Always wait in a loop that re-checks the predicate, because wake-ups can be spurious.
Blocks a group of threads until all of them reach the same point — for example, every worker finishing its share of a simulation tick before the next phase begins.
A promise is the write end and a future the read end of a value that will exist later. They let one thread hand a result to another without explicit locking: std::future, CompletableFuture, Task<T>.
A function that can suspend and resume, keeping its local state. C++20 co_await, C# async methods and Kotlin suspend functions all compile to state machines that let one thread juggle many waiting tasks.
A typed queue that transfers ownership of values between concurrent tasks, so they communicate instead of sharing memory. Buffered channels also give natural back-pressure.
The practices that keep a long-lived server codebase changeable and debuggable: proven structure, tests that catch regressions before players do, loose coupling between systems, and the ability to work out what happened from a crash.
Named solutions to recurring design problems — command, observer, state, object pool, component. Use them to communicate and to avoid reinventing, not as a checklist.
Write a failing test, make it pass, then refactor. On servers it pays off most for game rules, protocol parsing and economy logic, where bugs are expensive and deterministic tests are cheap.
Pass a component its collaborators (database, clock, network) instead of having it construct them, so you can swap in fakes for tests and different implementations per environment.
Capture a core dump or minidump when the server crashes and inspect stacks, threads and memory in gdb, lldb or WinDbg. Ship symbols for every build so production dumps are readable.
Pure functions and immutable data make concurrency safer: state transitions become newState = update(oldState, input), which is easy to test, replay and parallelise.
Persistent player data — accounts, inventories, progression, purchases — lives in databases that must never lose or duplicate it. Most games combine a relational store for transactional data, a NoSQL store for scale and a key-value cache for hot reads.
A group of operations that commits or rolls back as one, with ACID guarantees. Item trades and purchases must be transactional or players will find ways to duplicate items.
Maps tables to objects (Entity Framework, Hibernate, GORM) so you write less SQL. Watch for N+1 queries and hidden lazy loads on hot paths, and drop to raw SQL when needed.
A data access layer puts all persistence behind an interface such as a repository, so game logic never knows which database, cache or ORM sits underneath.
Splitting data or worlds across independent servers by a key such as player ID or region. It scales writes horizontally but makes cross-shard queries and transactions hard.
Relational databases give you schemas, joins, constraints and real transactions — the right home for accounts, entitlements and anything involving money.
Widely deployed open-source relational database, typically with the InnoDB engine; strong replication tooling and broad hosting support.
Feature-rich open-source database with strict SQL, JSONB, powerful indexing and extensions. A safe default for new game backends.
Microsoft SQL Server, common in .NET studios and on Azure, with mature tooling and T-SQL stored procedures.
Non-relational stores trade joins and rich transactions for flexible schemas and easy horizontal scaling. They suit player profiles, event logs and huge write volumes, provided you design around your access patterns.
Document database storing BSON documents with secondary indexes, aggregation pipelines and multi-document transactions. Model documents around how they are read.
Wide-column store with masterless replication built for very high write throughput across data centres. Tables are designed per query, with tunable consistency.
Distributed document database with a built-in memory-first cache and SQL-like querying (SQL++). Used by several large online games for profile data.
AWS's fully managed key-value and document database with single-digit-millisecond reads at any scale. Design the partition key carefully to avoid hot partitions.
In-memory key-value stores sit in front of the main database to serve hot data — sessions, leaderboards, matchmaking queues — in well under a millisecond.
In-memory data structure server: sorted sets make leaderboards trivial, plus TTLs, pub/sub, streams and Lua scripts. Configure persistence deliberately; it is not a primary database by default.
A simple, multithreaded in-memory cache of opaque values with LRU eviction and no persistence — pure caching with very little to configure.
How backend services talk to each other and to clients outside the real-time loop. REST over HTTP is the lingua franca for public APIs; RPC frameworks give typed, faster calls between internal services.
RPC over HTTP/2 with Protobuf contracts, generated clients, deadlines and bidirectional streaming. Well suited to internal services such as matchmaking or inventory.
Resources addressed by URLs and manipulated with HTTP methods and status codes. Make writes idempotent where possible so clients can safely retry on flaky mobile networks.
Brokers that decouple producers from consumers, absorbing spikes and letting work happen asynchronously — match results, analytics events, notifications, cross-server chat. Know the delivery guarantees you are getting and make consumers idempotent.
A general-purpose AMQP broker with exchanges, routing keys, acknowledgements and dead-letter queues — good for task distribution and routing messages between services.
A distributed, partitioned commit log retaining events for replay. The standard backbone for telemetry and event-driven pipelines; ordering holds within a partition only.
Rather than dedicating threads to subsystems, break work into small tasks and let a pool of workers — usually one per core, with work stealing — run them. It balances uneven loads automatically and is how modern engines and .NET's Task Parallel Library scale.
Structure the server as components that react to events — packets, timers, state changes — through non-blocking, message-driven pipelines. Reactive systems aim to stay responsive under load and failure by isolating components and applying back-pressure.
Data flows as asynchronous streams transformed by operators such as map, filter and merge, with subscribers signalling demand. Project Reactor, RxJava and Akka Streams implement it on the JVM.
Whether handlers run to completion before the next event (synchronous) or overlap (asynchronous). Synchronous processing keeps ordering obvious but one slow handler stalls everything queued behind it.
The same inputs in the same order must give the same outputs: no wall-clock reads, unordered hash iteration or unseeded randomness in game logic. It enables replays, lockstep networking and reproducing bugs.
The server tick: collect inputs, step the simulation at a fixed timestep, then publish state. A fixed rate (say 20–60 Hz) keeps physics stable and costs predictable.
Object-oriented reactive programming: objects expose observable properties and events, and dependents subscribe instead of polling. Natural in engines built around entities and components.
Functional reactive programming models time-varying values and event streams as first-class, composable values, so logic like cooldowns or interpolation becomes declarative transformations.
Start an operation, keep working and pick up the result later instead of blocking a thread. Each language has its own model, and a game server developer should know the idioms of the ones the team uses.
Start a function concurrently with go f(). The runtime multiplexes many thousands of goroutines on a few OS threads and parks them cheaply on network I/O; coordinate with channels, sync.WaitGroup and context.
ExecutorService, CompletableFuture, concurrent collections and, since Java 21, virtual threads that make blocking-style code scale like async code.
async methods return Task and suspend at await without blocking a thread. Avoid async void, never block on .Result in server code, and use ValueTask on hot paths.
Intel's oneTBB library: parallel_for, task groups, flow graphs and concurrent containers on a work-stealing scheduler, so C++ code scales without hand-managed threads.
Actors own their state privately and interact only by sending asynchronous messages, processing one message at a time. That removes locks from game logic — a player, room or match becomes an actor — and supervision handles failures. Erlang and Orleans are well-known examples.
The JVM actor toolkit for Java and Scala, with typed actors, clustering, sharding and persistence. Newer versions use a commercial licence; Apache Pekko is the open-source fork.
A community port of Akka to .NET with actors, remoting, clustering and persistence — useful for C# game backends that want actor-style concurrency.
An event loop waits for many sockets to become ready, then dispatches each to a handler that performs the non-blocking read or write. One thread can serve thousands of connections; Node.js, Netty, nginx and libuv all work this way.
The oldest readiness API: pass descriptor sets and get back those ready. Limited by FD_SETSIZE and O(n) per call, so only suitable for small numbers of sockets.
WSAPoll is Windows' version of poll. It is simpler than select but does not scale like IOCP, and older Windows builds had bugs with failed connects.
Linux's scalable readiness API: register sockets once with epoll_ctl, then epoll_wait returns only those ready. Learn the difference between level- and edge-triggered modes.
The BSD and macOS event notification interface, covering sockets, files, signals and timers through one kevent call.
Instead of waiting for readiness, you submit the I/O operation itself and get notified when it has completed. The kernel does the copy, which cuts system calls and suits very high packet rates.
Windows I/O completion ports: issue overlapped WSARecv/WSASend calls and a pool of threads drains completions from the port. The standard high-performance server model on Windows.
Linux's completion-based interface using shared submission and completion rings, batching many operations per system call. Some container platforms disable it for security reasons.
Windows RIO pre-registers buffers and uses request and completion queues to cut per-operation overhead, aimed at very high rates of small UDP packets.
Package each server build with its dependencies into an image that runs the same on a laptop and in production. Containers make it practical to spin game-server instances up and down with demand.
Build images from a Dockerfile, run them as isolated processes, and publish UDP ports explicitly (-p 7777:7777/udp). Multi-stage builds keep server images small.
Define a local stack — game server, database, Redis, broker — in one compose.yaml and start it with docker compose up.
Orchestrates containers across a cluster with scheduling, health checks and autoscaling. Agones extends it for dedicated game servers, handling allocation and not killing servers mid-match.
Renting compute, storage and managed services instead of running data centres. For games the draw is global regions close to players and elastic capacity for launch days; the risk is egress bandwidth costs and lock-in.
The largest provider; GameLift offers managed dedicated-server hosting and matchmaking alongside EC2, DynamoDB and Lambda.
Microsoft's cloud, closely tied to .NET and Xbox services, with PlayFab for game backend features such as accounts, economy and multiplayer servers.
Google Cloud, strong in Kubernetes (GKE, home of Agones), data analytics with BigQuery and a global private network.
Event-triggered functions billed per invocation, with no servers to manage. Good for bursty backend work like receipts validation, webhooks and leaderboard writes; unsuitable for stateful real-time sessions.
Two meanings meet here: running data stores as clusters for capacity and availability, and grouping players by behaviour with clustering algorithms for matchmaking, churn prediction and cheat detection. Both rely on distributed processing of large telemetry sets.
A distributed engine for batch and streaming analytics over large datasets, with SQL, DataFrames and the MLlib library (including k-means clustering).
On the server side, machine learning powers matchmaking quality, cheat and fraud detection, churn prediction and content recommendations. You need enough understanding to feed models good data and serve their predictions within latency budgets.
Managed platforms that handle training infrastructure, model registries and hosted inference endpoints, so a small backend team can use ML without running GPU clusters.
Neural networks with many layers, trained on large datasets. In games they drive bots, toxicity detection in chat and player modelling; serving them efficiently usually means batching, quantisation or a separate inference service.
Google's framework with Keras as its high-level API and TensorFlow Serving for production inference.
The dominant research and increasingly production framework, with eager execution, torch.compile and export paths such as ONNX for serving.