Master-to-Replica Sync in Go
Companion to the main guide's Replication. That section describes the handshake, the RDB transfer, and the live command stream in prose. This file makes that wire protocol concrete — two Go processes talking over a real TCP socket. Read the backlog companion for the master's internal data structures; this one is about the conversation that crosses the wire. Both are learning sketches, not ports of the C source — but the control flow and the byte-level protocol are real.
The Conversation We're Implementing
Everything below concatenates into one runnable main.go.
RESP Encoding — and Why We Count Bytes
main.go
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
)
// encodeArray builds a RESP array: *2\r\n$3\r\nGET\r\n$3\r\nfoo\r\n
func encodeArray(parts ...string) []byte {
var b bytes.Buffer
fmt.Fprintf(&b, "*%d\r\n", len(parts))
for _, p := range parts {
fmt.Fprintf(&b, "$%d\r\n%s\r\n", len(p), p)
}
return b.Bytes()
}readArray returns the parsed command and the number of bytes it consumed. That second return value is the whole reason replication offsets work:
main.go (continued)
// readArray parses one RESP array and reports how many raw bytes it ate.
// The byte count matters: a replica's offset is a position in the byte
// stream, NOT a count of commands. Miscount by one and every subsequent
// partial resync asks the master for the wrong place in the backlog.
func readArray(r *bufio.Reader) ([]string, int64, error) {
line, err := r.ReadString('\n')
if err != nil {
return nil, 0, err
}
consumed := int64(len(line))
line = strings.TrimRight(line, "\r\n")
if len(line) == 0 || line[0] != '*' {
return nil, 0, fmt.Errorf("expected array, got %q", line)
}
n, err := strconv.Atoi(line[1:])
if err != nil {
return nil, 0, err
}
out := make([]string, 0, n)
for i := 0; i < n; i++ {
hdr, err := r.ReadString('\n') // $<len>\r\n
if err != nil {
return nil, 0, err
}
consumed += int64(len(hdr))
ln, err := strconv.Atoi(strings.TrimRight(hdr, "\r\n")[1:])
if err != nil {
return nil, 0, err
}
buf := make([]byte, ln+2) // payload + trailing CRLF
if _, err := io.ReadFull(r, buf); err != nil {
return nil, 0, err
}
consumed += int64(ln + 2)
out = append(out, string(buf[:ln]))
}
return out, consumed, nil
}
func readLine(r *bufio.Reader) (string, error) {
line, err := r.ReadString('\n')
return strings.TrimRight(line, "\r\n"), err
}The Backlog (Deliberately Simplified)
main.go (continued)
// Backlog holds the recent replication stream so a briefly-disconnected
// replica can be caught up without a full resync.
type Backlog struct {
buf []byte
base int64 // repl offset of buf[0]
}
func (b *Backlog) Feed(p []byte) { b.buf = append(b.buf, p...) }
func (b *Backlog) End() int64 { return b.base + int64(len(b.buf)) }
func (b *Backlog) CanServe(off int64) bool {
return off >= b.base && off <= b.End()
}
func (b *Backlog) Since(off int64) []byte {
return b.buf[off-b.base:]
}Master: State
main.go (continued)
type replicaConn struct {
id string
conn net.Conn
ack int64 // last offset this replica confirmed receiving
}
type Master struct {
mu sync.Mutex
store map[string]string
replID string // this master's replication ID (40 hex chars in real Redis)
replOffset int64
backlog Backlog
replicas map[string]*replicaConn
}
func NewMaster() *Master {
return &Master{
store: map[string]string{},
replID: "8371b4fb1155b71f4a04d3e1bc3e18c4a990aeeb",
replicas: map[string]*replicaConn{},
}
}Master: Propagation
The single place a write fans out. Note what it does not do: it never reads the AOF to decide what to send. AOF and replication are two independent consumers of the same executed command.
main.go (continued)
// Propagate is called immediately after a write command executes.
// Caller must hold m.mu — mirroring real Redis, where this happens on the
// single main thread with no lock needed at all.
func (m *Master) propagateLocked(cmd []byte) {
m.backlog.Feed(cmd)
m.replOffset += int64(len(cmd))
for _, r := range m.replicas {
// Real Redis: non-blocking write into the replica's output buffer.
// A replica too slow to drain it eventually gets disconnected.
_, _ = r.conn.Write(cmd)
}
}
func (m *Master) Set(k, v string) {
m.mu.Lock()
defer m.mu.Unlock()
m.store[k] = v
m.propagateLocked(encodeArray("SET", k, v))
}Master: The Handshake Handler
main.go (continued)
func (m *Master) Serve(ln net.Listener) {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go m.handleConn(conn)
}
}
func (m *Master) handleConn(conn net.Conn) {
r := bufio.NewReader(conn)
for {
args, _, err := readArray(r)
if err != nil {
conn.Close()
return
}
switch strings.ToUpper(args[0]) {
case "PING":
conn.Write([]byte("+PONG\r\n"))
case "REPLCONF":
// listening-port / capa — the master just acknowledges.
conn.Write([]byte("+OK\r\n"))
case "SET":
m.Set(args[1], args[2])
conn.Write([]byte("+OK\r\n"))
case "PSYNC":
// Hand the SAME bufio.Reader over — it may already hold buffered
// bytes. Creating a fresh reader here would silently drop them.
m.handlePSYNC(conn, r, args[1], args[2])
return // this goroutine's request/response job is done
}
}
}Master: PSYNC — Full vs. Partial
main.go (continued)
func (m *Master) handlePSYNC(conn net.Conn, r *bufio.Reader, wantID, wantOff string) {
m.mu.Lock()
id := conn.RemoteAddr().String()
off, _ := strconv.ParseInt(wantOff, 10, 64)
if wantID == m.replID && off >= 0 && m.backlog.CanServe(off) {
// PARTIAL: replica was here recently and we still hold its bytes.
conn.Write([]byte("+CONTINUE\r\n"))
conn.Write(m.backlog.Since(off))
} else {
// FULL: unknown replid, or backlog no longer covers that offset.
fmt.Fprintf(conn, "+FULLRESYNC %s %d\r\n", m.replID, m.replOffset)
rdb := m.serializeLocked()
// Length-prefixed with NO trailing CRLF — an RDB payload is binary,
// not a RESP bulk string. Diskless mode instead uses $EOF:<40-byte
// delimiter> because the length isn't known before the fork streams.
fmt.Fprintf(conn, "$%d\r\n", len(rdb))
conn.Write(rdb)
off = m.replOffset
}
// Register only AFTER the snapshot is on the wire, still under the lock.
// This is the critical window: register too early and the replica gets a
// command twice (once in the RDB, once in the stream); too late and it
// misses one entirely. Real Redis gets this free from single-threading.
m.replicas[id] = &replicaConn{id: id, conn: conn, ack: off}
m.mu.Unlock()
go m.readAcks(conn, r, id)
}
// serializeLocked stands in for BGSAVE's fork + RDB serialization.
func (m *Master) serializeLocked() []byte {
var b bytes.Buffer
for k, v := range m.store {
fmt.Fprintf(&b, "%s=%s;", k, v)
}
return b.Bytes()
}
// readAcks consumes REPLCONF ACK <offset> arriving back up the same socket.
func (m *Master) readAcks(conn net.Conn, r *bufio.Reader, id string) {
defer conn.Close()
for {
args, _, err := readArray(r)
if err != nil {
m.mu.Lock()
delete(m.replicas, id)
m.mu.Unlock()
return
}
if len(args) == 3 && strings.EqualFold(args[0], "REPLCONF") &&
strings.EqualFold(args[1], "ACK") {
off, _ := strconv.ParseInt(args[2], 10, 64)
m.mu.Lock()
if rc, ok := m.replicas[id]; ok {
rc.ack = off
}
m.mu.Unlock()
}
}
}Replica: The Client Side of the Handshake
main.go (continued)
type Replica struct {
mu sync.Mutex
name string
port string
store map[string]string
masterID string // learned from +FULLRESYNC; enables later partial resync
offset int64
}
func NewReplica(name, port string) *Replica {
return &Replica{name: name, port: port, store: map[string]string{}, offset: -1}
}
func (rp *Replica) ConnectTo(addr string) error {
conn, err := net.Dial("tcp", addr)
if err != nil {
return err
}
r := bufio.NewReader(conn)
// Step 1 — liveness probe.
conn.Write(encodeArray("PING"))
if line, _ := readLine(r); line != "+PONG" {
return fmt.Errorf("bad PING reply: %q", line)
}
// Step 2 — tell the master our port, so it shows up in INFO replication.
conn.Write(encodeArray("REPLCONF", "listening-port", rp.port))
readLine(r)
// Step 3 — advertise capabilities (psync2 = partial resync after failover).
conn.Write(encodeArray("REPLCONF", "capa", "eof", "capa", "psync2"))
readLine(r)
// Step 4 — PSYNC. First connection sends "? -1": no known master, no offset.
id := rp.masterID
if id == "" {
id = "?"
}
conn.Write(encodeArray("PSYNC", id, strconv.FormatInt(rp.offset, 10)))
reply, err := readLine(r)
if err != nil {
return err
}
switch {
case strings.HasPrefix(reply, "+FULLRESYNC"):
f := strings.Fields(reply)
rp.masterID = f[1]
rp.offset, _ = strconv.ParseInt(f[2], 10, 64)
if err := rp.loadRDB(r); err != nil {
return err
}
fmt.Printf("[%s] FULLRESYNC at offset %d\n", rp.name, rp.offset)
case strings.HasPrefix(reply, "+CONTINUE"):
fmt.Printf("[%s] CONTINUE from offset %d — no RDB needed\n", rp.name, rp.offset)
default:
return fmt.Errorf("unexpected PSYNC reply: %q", reply)
}
go rp.ackLoop(conn)
go rp.streamLoop(r)
return nil
}
func (rp *Replica) loadRDB(r *bufio.Reader) error {
hdr, err := readLine(r) // $<len>
if err != nil {
return err
}
n, err := strconv.Atoi(hdr[1:])
if err != nil {
return err
}
buf := make([]byte, n)
if _, err := io.ReadFull(r, buf); err != nil {
return err
}
rp.mu.Lock()
defer rp.mu.Unlock()
rp.store = map[string]string{} // full resync REPLACES the dataset
for _, pair := range strings.Split(string(buf), ";") {
if kv := strings.SplitN(pair, "=", 2); len(kv) == 2 {
rp.store[kv[0]] = kv[1]
}
}
return nil
}Replica: The Live Stream and the ACK Loop
main.go (continued)
// streamLoop is the steady state — read commands forever, apply, advance
// the offset by the BYTES consumed. Note there is no reply written here:
// the replica never answers the master on the replication link.
func (rp *Replica) streamLoop(r *bufio.Reader) {
for {
args, n, err := readArray(r)
if err != nil {
fmt.Printf("[%s] link to master lost\n", rp.name)
return
}
rp.mu.Lock()
if strings.EqualFold(args[0], "SET") {
rp.store[args[1]] = args[2]
}
rp.offset += n // ← byte count, not command count
rp.mu.Unlock()
}
}
// ackLoop reports progress roughly once a second. This is what feeds the
// master's per-replica ack offset, and therefore what WAIT blocks on.
func (rp *Replica) ackLoop(conn net.Conn) {
t := time.NewTicker(200 * time.Millisecond) // 1s in real Redis
defer t.Stop()
for range t.C {
rp.mu.Lock()
off := rp.offset
rp.mu.Unlock()
if _, err := conn.Write(encodeArray("REPLCONF", "ACK",
strconv.FormatInt(off, 10))); err != nil {
return
}
}
}
func (rp *Replica) Get(k string) string {
rp.mu.Lock()
defer rp.mu.Unlock()
return rp.store[k]
}Runnable Demo
main.go (continued)
func main() {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
panic(err)
}
addr := ln.Addr().String()
m := NewMaster()
go m.Serve(ln)
// Pre-existing data — this is what the RDB snapshot must carry over.
m.Set("user:1", "alice")
m.Set("user:2", "bob")
r1 := NewReplica("replica-1", "6380")
r2 := NewReplica("replica-2", "6381")
r1.ConnectTo(addr)
r2.ConnectTo(addr)
// Both replicas got the snapshot; now stream live writes.
m.Set("user:3", "carol")
m.Set("user:1", "alice-updated")
time.Sleep(300 * time.Millisecond)
fmt.Println("r1 user:1 =", r1.Get("user:1")) // alice-updated (streamed)
fmt.Println("r2 user:3 =", r2.Get("user:3")) // carol (streamed)
fmt.Println("r1 user:2 =", r1.Get("user:2")) // bob (from RDB)
m.mu.Lock()
fmt.Printf("master offset=%d, replicas=%d\n", m.replOffset, len(m.replicas))
for _, rc := range m.replicas {
fmt.Printf(" %s acked %d\n", rc.id, rc.ack)
}
m.mu.Unlock()
}Add a r3 := NewReplica(...) that connects, then reconnects with its saved masterID and offset, to watch the +CONTINUE path fire instead of +FULLRESYNC. In this sketch it always succeeds because the backlog is unbounded — swap in the circular buffer from the backlog companion to make it realistically fail and fall back to a full resync.
How This Maps Back to the Real Thing
| In this Go sketch | In real Redis |
|---|---|
Replica.ConnectTo step sequence | syncWithMaster() state machine in replication.c (REPL_STATE_*) |
Master.handlePSYNC | syncCommand() + masterTryPartialResynchronization() |
Master.propagateLocked | replicationFeedSlaves() |
Replica.streamLoop | replica's master-client, fed through the normal command executor |
Replica.ackLoop | replicationSendAck(), driven by replicationCron() every 1s |
Master.readAcks | replconfCommand() handling ACK |
serializeLocked() | fork() + rdbSaveToSlavesSockets() / disk-backed BGSAVE |
replID | server.replid — 40 hex chars, regenerated on promotion |
What's simplified away
- The fork.
serializeLockedruns inline; real Redis forks a child so the master keeps serving during the snapshot. That fork is also the latency trap covered at fork() Latency Trap in the main guide. - BGSAVE sharing. Two replicas connecting close together should ride one fork; here each gets its own serialization pass.
- Backpressure. Real per-replica output buffers have limits (
client-output-buffer-limit replica ...); a replica too slow to drain gets disconnected. Hereconn.Writejust blocks. - The mutex. It stands in for single-threadedness. Real Redis touches all of this serially between commands, so no lock exists in the C.
replid2/ failover continuity.psync2lets a promoted replica keep serving partial resyncs to its siblings using the old master's replid. That's the whole reason the capability is negotiated in step 3, and it's why a failover doesn't force every surviving replica into a full resync.
- Faithful: The handshake order, the request/response → one-way-stream transition at
PSYNC, offsets as byte positions, the RDB-then-delta ordering, and the registration window inhandlePSYNCwhere getting the ordering wrong duplicates or drops a command. - Not faithful: Forking, buffer backpressure, and lock-free single-threaded execution — see "What's simplified away" above.
Related pages
- ← Back to the full guide — Single-threading, memory, persistence, replication, cluster, HA, rate limiting, and the protocol deep-dives.
- The backlog, coded → — The master's internal circular buffer, per-replica offsets, and WAIT — the data structures behind this wire protocol.