Replication Backlog and Per-Replica Offsets in Go

Companion to the main guide's Replication, specifically the repl_backlog circular buffer, per-replica repl_ack_offset, and how PSYNC decides partial vs. full resync. This file makes those mechanics concrete with a small, runnable Go implementation — a simulation for learning purposes, not a port of real Redis's C source, but the data structures and control flow mirror the real thing closely enough to build correct intuition. Read the wire-protocol companion for what actually crosses the socket between master and replica; this one is about the master's internal state.

What We're Modeling

Three moving parts, all owned by the master:

  • ReplBacklog — one shared, fixed-size circular buffer of RESP bytes. Old bytes get overwritten as new ones arrive; the buffer tracks the lowest offset it can still serve.
  • ReplicaConn — one per connected replica, holding only a live socket handle and that replica's last-known AckOffset. The backlog is never duplicated per replica.
  • Master.Propagate — the single call site that feeds both the backlog and every live replica socket, in lockstep, the moment a write command executes.

ReplBacklog — the Circular Buffer

replication/backlog.go

package replication

import (
	"fmt"
	"sync"
	"time"
)

// ReplBacklog is a fixed-size circular buffer of RESP-encoded command bytes.
type ReplBacklog struct {
	buf      []byte
	capacity int
	histlen  int   // valid bytes currently held, <= capacity
	writePos int   // next write index in buf
	offset   int64 // repl_offset corresponding to the oldest byte still held
}

func NewReplBacklog(capacity int) *ReplBacklog {
	return &ReplBacklog{buf: make([]byte, capacity), capacity: capacity, offset: 1}
}

func (b *ReplBacklog) Feed(data []byte) {
	n := len(data)
	for _, c := range data {
		b.buf[b.writePos] = c
		b.writePos = (b.writePos + 1) % b.capacity
	}
	if b.histlen+n <= b.capacity {
		b.histlen += n
	} else {
		overwritten := (b.histlen + n) - b.capacity
		b.histlen = b.capacity
		b.offset += int64(overwritten) // oldest recoverable point moves forward
	}
}

// CanServeFrom answers: is requestedOffset still inside the window we hold?
func (b *ReplBacklog) CanServeFrom(requestedOffset, masterReplOffset int64) bool {
	return requestedOffset >= b.offset && requestedOffset <= masterReplOffset
}

// GetRange extracts the byte range [start, end) from the circular buffer.
// Caller must have already checked CanServeFrom.
func (b *ReplBacklog) GetRange(start, end int64) []byte {
	skip := int(start - b.offset)
	length := int(end - start)
	readPos := (((b.writePos-b.histlen)%b.capacity)+b.capacity)%b.capacity + skip
	readPos %= b.capacity

	out := make([]byte, length)
	for i := 0; i < length; i++ {
		out[i] = b.buf[(readPos+i)%b.capacity]
	}
	return out
}

ReplicaConn & Master State

replication/backlog.go (continued)

// ReplicaConn is one connected replica's live send path plus its
// independently tracked ack offset. Nothing else is per-replica state —
// the backlog itself is shared.
type ReplicaConn struct {
	ID        string
	Send      func([]byte) error // stand-in for conn.Write on the real TCP socket
	AckOffset int64
}

type Master struct {
	mu         sync.Mutex
	replOffset int64
	backlog    *ReplBacklog
	replicas   map[string]*ReplicaConn
}

func NewMaster(backlogCapacity int) *Master {
	return &Master{
		backlog:  NewReplBacklog(backlogCapacity),
		replicas: map[string]*ReplicaConn{},
	}
}

Propagate — Feeding Backlog + Replicas

replication/backlog.go (continued)

// Propagate is called right after a write command executes on the main
// thread. This single call feeds BOTH the backlog and every live replica —
// there is no "read the AOF, then forward it" step; AOF and replication
// are two independent consumers of the same command.
func (m *Master) Propagate(cmd []byte) {
	m.mu.Lock()
	defer m.mu.Unlock()

	m.backlog.Feed(cmd)
	m.replOffset += int64(len(cmd))

	for _, r := range m.replicas {
		_ = r.Send(cmd) // real Redis: non-blocking write into the replica's socket buffer
	}
}

// OnReplconfAck updates one replica's ack offset. Real replicas send
// `REPLCONF ACK <offset>` back to the master roughly once a second.
func (m *Master) OnReplconfAck(replicaID string, offset int64) {
	m.mu.Lock()
	defer m.mu.Unlock()
	if r, ok := m.replicas[replicaID]; ok {
		r.AckOffset = offset
	}
}

HandlePSYNC — Partial vs. Full

Decides partial vs. full resync exactly like real Redis: if requestedOffset is still inside the backlog window, ship only the delta; otherwise trigger a full RDB resync.

replication/backlog.go (continued)

func (m *Master) HandlePSYNC(replicaID string, send func([]byte) error, requestedOffset int64) {
	m.mu.Lock()
	defer m.mu.Unlock()

	if requestedOffset != -1 && m.backlog.CanServeFrom(requestedOffset, m.replOffset) {
		delta := m.backlog.GetRange(requestedOffset, m.replOffset)
		_ = send([]byte("+CONTINUE\r\n"))
		_ = send(delta)
	} else {
		rdbOffset := m.replOffset
		rdb := m.bgsave() // snapshot of state AT rdbOffset
		_ = send([]byte(fmt.Sprintf("+FULLRESYNC %s %d\r\n", "replid-demo", rdbOffset)))
		_ = send(rdb)
		// anything the backlog collected DURING the fork/transfer:
		delta := m.backlog.GetRange(rdbOffset, m.replOffset)
		_ = send(delta)
	}

	m.replicas[replicaID] = &ReplicaConn{ID: replicaID, Send: send, AckOffset: requestedOffset}
}

func (m *Master) bgsave() []byte {
	return []byte("<RDB SNAPSHOT BYTES>")
}

Wait — Backing the WAIT Command

replication/backlog.go (continued)

// Wait blocks until numReplicas have ACKed at least the current repl
// offset, or timeout elapses. This is what backs the real WAIT command.
func (m *Master) Wait(numReplicas int, timeout time.Duration) int {
	m.mu.Lock()
	target := m.replOffset
	m.mu.Unlock()

	deadline := time.Now().Add(timeout)
	for {
		m.mu.Lock()
		acked := 0
		for _, r := range m.replicas {
			if r.AckOffset >= target {
				acked++
			}
		}
		m.mu.Unlock()

		if acked >= numReplicas || time.Now().After(deadline) {
			return acked
		}
		time.Sleep(time.Millisecond)
	}
}

Demo: Wraparound Forcing a Full Resync

A tiny 32-byte backlog makes the wraparound (and the resulting full resync) happen after just a few writes — with a real 1 MB+ backlog the same thing happens, just after much more traffic.

replication/main.go

func main() {
	m := NewMaster(32) // tiny on purpose, to force wraparound fast

	send := func(label string) func([]byte) error {
		return func(b []byte) error {
			fmt.Printf("[%s] <- %q\n", label, b)
			return nil
		}
	}

	// Two replicas do their initial full resync (requestedOffset == -1)
	m.HandlePSYNC("replica-1", send("replica-1"), -1)
	m.HandlePSYNC("replica-2", send("replica-2"), -1)

	for i := 0; i < 5; i++ {
		cmd := []byte(fmt.Sprintf("SET k%d v%d;", i, i))
		m.Propagate(cmd)
		m.OnReplconfAck("replica-1", m.replOffset)
		m.OnReplconfAck("replica-2", m.replOffset)
	}

	acked := m.Wait(2, 100*time.Millisecond)
	fmt.Println("replicas caught up:", acked)

	// replica-3 reconnects claiming offset=2 — but the 32-byte backlog has
	// long since wrapped past that point, so CanServeFrom fails and this
	// falls into the FULLRESYNC branch instead of +CONTINUE.
	m.HandlePSYNC("replica-3", send("replica-3"), 2)
}

How This Maps Back to the Real Thing

In this Go sketchIn real Redis
ReplBacklog.buf ([]byte, fixed size)server.repl_backlog — default 1 MB, repl-backlog-size
ReplBacklog.offsetserver.repl_backlog_off
Master.replOffsetserver.master_repl_offset
Master.PropagatereplicationFeedSlaves() in replication.c
ReplicaConn.AckOffsetper-client slave->repl_ack_off, updated on REPLCONF ACK
Master.WaitwaitCommand() — same idea, real one also accounts for already-satisfied fast path
Master.HandlePSYNCsyncCommand() / masterTryPartialResynchronization()
  • Faithful: The control flow and offset arithmetic — how a circular buffer's oldest-servable offset advances on wraparound, and how that boundary alone decides partial vs. full resync.
  • Not faithful: Real Redis fan-out happens over actual non-blocking sockets with per-connection output buffers and backpressure (a slow replica can build up an output buffer and eventually get disconnected as O(output buffer size) too large). The mutex here stands in for the fact that Redis's core command loop is single-threaded, so no lock is actually needed in C — replication state is just touched serially between commands.
  • ← Back to the full guide — Single-threading, memory, persistence, replication, cluster, HA, rate limiting, and the protocol deep-dives.
  • The wire protocol, coded → — The handshake, PSYNC, and the live command stream — what actually crosses the socket between master and replica.