Replication: Master to read-only replica
Replication is two phases. Bulk transfer: catch the replica up to current state. Streaming: every subsequent write is shipped to the replica as it happens. Real Redis adds checksums and resync offsets, our version skips those for clarity. The shape is identical.
How a replica catches up and stays caught up
if isinstance(cmd, list) and cmd and str(cmd[0]).upper() == "SYNC":
print(f" [master] {addr} requested SYNC, sending {len(STORE)} keys")
for k, v in list(STORE.items()):
client.sendall(encode_array(["SET", k, v]))
with REPLICA_LOCK:
REPLICA_SOCKETS.append(client)
sync_mode = True
return # leave the socket open; main loop has more clientsWhen a client sends SYNC, master walks the store, sends one SET per key, then leaves the socket alive in REPLICA_SOCKETS. Every subsequent write fans out to every socket in that list.
def replicate_to_all(frame):
"""Master: ship a successful write command to every replica."""
payload = encode_array([str(x) for x in frame])
with REPLICA_LOCK:
replicas = list(REPLICA_SOCKETS)
for s in replicas:
try:
s.sendall(payload)
except OSError:
with REPLICA_LOCK:
if s in REPLICA_SOCKETS:
REPLICA_SOCKETS.remove(s)On the master, every successful write is fanned out to every replica socket. Same RESP we already had. No new wire format.
If both nodes accepted writes, they would diverge. The replica must apply only what comes from the master stream. Client SETs land in different keys, replication has no way to reconcile. Standard fix: replicas are read-only, writes go to the master.