Reliability over UDP: Acks & Bitfields
UDP gives you no delivery guarantees, and TCP gives you too many (TCP vs UDP for Games). Game protocols sit in between: a small header on every UDP packet tells the other side which packets arrived, and on top of that the game decides, per message, whether to resend it. This lesson builds the classic scheme, used in many shipped games and libraries, step by step.
The packet header
Every packet, in both directions, starts with:
| Field | Size | Meaning |
|---|---|---|
sequence |
16 bits | this packet's number, +1 for every packet sent |
ack |
16 bits | the newest sequence number received from the other side |
ackBits |
32 bits | bit i set = packet ack - 1 - i was also received |
So each packet acknowledges 33 packets at once. At 30 packets per second that is a whole second of history: an ack is only lost if every packet in that second carrying it is lost. Nothing is ever acked "on its own"; acks ride on the normal traffic for free.
Sequence numbers wrap around
At 60 packets per second, a 16-bit sequence wraps from 65535 to 0 after about 18 minutes. Comparing with > then breaks. Treat the numbers as a circle instead: a is newer than b if it is less than half the circle ahead:
function seqGreater(a: number, b: number): boolean { // 16-bit sequence numbers
return (a > b && a - b <= 32768) || (a < b && b - a > 32768);
}
function seqDiff(a: number, b: number): number { // how far a is ahead of b
return ((a - b + 32768) & 0xffff) - 32768;
}
const pairs: [number, number][] = [[5, 3], [3, 5], [0, 65535], [65535, 0], [10, 65530], [40000, 100]];
for (const [a, b] of pairs) {
console.log(`${String(a).padStart(5)} newer than ${String(b).padStart(5)}? ${String(seqGreater(a, b)).padEnd(5)} diff ${seqDiff(a, b)}`);
} 5 newer than 3? true diff 2
3 newer than 5? false diff -2
0 newer than 65535? true diff 1
65535 newer than 0? false diff -1
10 newer than 65530? true diff 16
40000 newer than 100? false diff -25636
Acks and the bitfield
The receiver keeps the newest sequence it has seen and a 32-bit mask of the ones before it. When a packet arrives, it either becomes the new newest (shift the mask) or sets one bit. The sender keeps a small ring buffer of what it sent and, for every packet it receives, reads the header and marks its own sent packets as acknowledged:
class AckState {
ack = -1; // newest sequence received (-1 = none yet)
bits = 0; // bit i: received ack - 1 - i
onReceive(seq: number) {
if (this.ack < 0) { this.ack = seq; return; }
const d = seq - this.ack; // no wrap in this small demo
if (d > 0) {
this.bits = d >= 32 ? 0 : ((this.bits << d) | (1 << (d - 1))) >>> 0;
this.ack = seq;
} else if (d < 0 && -d <= 32) {
this.bits = (this.bits | (1 << (-d - 1))) >>> 0; // a late, out-of-order packet
}
}
/** Which sequences does this header acknowledge? */
acked(): number[] {
const out = [this.ack];
for (let i = 0; i < 32; i++) if ((this.bits >>> i) & 1) out.push(this.ack - 1 - i);
return out.sort((a, b) => a - b);
}
}
const rx = new AckState();
const arrivals = [0, 1, 3, 4, 2, 7, 8]; // 5 and 6 lost; 2 arrives late
for (const seq of arrivals) {
rx.onReceive(seq);
console.log(`got ${seq}: ack=${rx.ack} bits=${rx.bits.toString(2).padStart(8, '0')} acks [${rx.acked().join(',')}]`);
}got 0: ack=0 bits=00000000 acks [0]
got 1: ack=1 bits=00000001 acks [0,1]
got 3: ack=3 bits=00000110 acks [0,1,3]
got 4: ack=4 bits=00001101 acks [0,1,3,4]
got 2: ack=4 bits=00001111 acks [0,1,2,3,4]
got 7: ack=7 bits=01111100 acks [0,1,2,3,4,7]
got 8: ack=8 bits=11111001 acks [0,1,2,3,4,7,8]
When the sender sees a sent packet fall more than 32 behind the newest ack without its bit being set, it knows that packet was lost. Counting those gives you a live packet-loss figure for free, and the time from sending to ack gives you RTT samples.
Reliable messages on top
Acks tell you which packets arrived. Reliability for messages is built on top: the sender remembers which messages went into which packet. A reliable message is put into packets again and again (say, every 100 ms, or into every packet while there is room) until one of those packets is acked. The receiver drops duplicates by message id and, for an ordered channel, holds messages until the gaps before them are filled.
Here is the whole loop with a lossy link. The client sends one packet per tick to the server; reliable chat messages ride inside; the server's replies carry acks back (the reply path is lossless here, to keep the output short):
function mulberry32(seed: number) {
return () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const rnd = mulberry32(29);
const LOSS = 0.3;
type Msg = { id: number; text: string };
const outbox: Msg[] = [{ id: 0, text: 'hi' }, { id: 1, text: 'gg' }, { id: 2, text: 'rematch?' }];
const inFlight = new Map<number, number[]>(); // packet seq -> message ids it carried
const received = new Map<number, string>(); // server: message id -> text
let nextDeliver = 0; // ordered channel: next id to hand to the game
let seq = 0;
for (let tick = 0; tick < 8; tick++) {
// Client: put every unacked message (max 2) into this tick's packet.
const carry = outbox.slice(0, 2);
inFlight.set(seq, carry.map((m) => m.id));
const lost = rnd() < LOSS;
let line = `tick ${tick}: packet ${seq} carries [${carry.map((m) => m.id).join(',')}]`;
if (lost) line += ' -> LOST';
else {
// Server: dedupe, store, deliver in order, and ack this packet in its reply.
const fresh = carry.filter((m) => !received.has(m.id));
for (const m of carry) received.set(m.id, m.text);
const delivered: string[] = [];
while (received.has(nextDeliver)) delivered.push(received.get(nextDeliver++)!);
line += ` -> server got ${fresh.length} new, delivered ${JSON.stringify(delivered)}`;
// Client: the reply acks packet `seq`, so the messages it carried are done.
for (const id of inFlight.get(seq)!) {
const i = outbox.findIndex((m) => m.id === id);
if (i >= 0) outbox.splice(i, 1);
}
}
console.log(line);
seq++;
if (outbox.length === 0) { console.log('all reliable messages acknowledged'); break; }
}tick 0: packet 0 carries [0,1] -> LOST
tick 1: packet 1 carries [0,1] -> LOST
tick 2: packet 2 carries [0,1] -> server got 2 new, delivered ["hi","gg"]
tick 3: packet 3 carries [2] -> LOST
tick 4: packet 4 carries [2] -> server got 1 new, delivered ["rematch?"]
all reliable messages acknowledged
Packets 0, 1 and 3 were lost (30% loss is brutal), yet every message arrived exactly once and in order: unacked messages simply ride along in the next packet until one gets through. If the server's reply had been lost instead, the client would send the messages again and the server's de-duplication by message id would drop the copies. That is why reliable messages need ids, and why the receiver, not the sender, guarantees "exactly once".
What real libraries add
- Resend timing based on RTT, so a message isn't stuffed into every packet when the link is fine.
- Fragmentation of big reliable messages (a map file, a long chat log) into packet-sized pieces with their own acks.
- Several channels: unreliable, unreliable-sequenced (drop older ones), reliable-unordered, reliable-ordered. A stall on the ordered chat channel must not delay the unreliable movement channel.
- Connection management: a handshake with a challenge (so spoofed source addresses can't open connections), timeouts and keep-alives (Connections, Timeouts & Reconnects).
- Encryption and authentication of every packet, so nobody on the path can read or forge them.
You rarely write this yourself in production: ENet, Valve's GameNetworkingSockets, yojimbo, LiteNetLib, Unity Transport and the engines' built-in layers all do it. But you will configure their channels and read their stats, and knowing what an ack bitfield is makes those settings make sense.
Test yourself
With a 16-bit sequence and a 32-bit ack bitfield, how many packets can one header acknowledge?
- 1
- 16
- 32
- 33
Is sequence 3 newer than sequence 65530 (16-bit, with wrap-around)?
- No, 3 is smaller
- Yes: going forward from 65530, 3 is only 9 steps ahead
- They are equal
- It can't be decided
A reliable message's packet was lost. How does the sender find out?
- The receiver sends a NACK packet immediately
- The packet's sequence never shows up in the acks of later packets, so the message is resent
- UDP reports it
- The router tells the sender