TASK
Implementation
Ensure read-your-writes consistency even when using follower reads. Clients send their last_write_index with each read. Followers only serve if they have applied that index.
Request: {"type": "write", "msg_id": 1, "key": "x", "value": "new"}
Response: {"type": "write_ok", "in_reply_to": 1, "commit_index": 10}
Request: {"type": "ryw_read", "msg_id": 2, "key": "x", "last_write_index": 10, "prefer_follower": true}
Response: {"type": "ryw_read_ok", "in_reply_to": 2, "value": "new", "served_by": "n2", "follower_applied_index": 10, "waited_ms": 50}
Request: {"type": "ryw_read", "msg_id": 3, "key": "x", "last_write_index": 15, "prefer_follower": true}
Response: {"type": "ryw_read_ok", "in_reply_to": 3, "value": "new", "served_by": "n1", "reason": "follower_behind_redirected_to_leader"}Sample Test Cases
Read-your-writes from followerTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1","n2","n3"]}}
{"src":"c1","dest":"n1","body":{"type":"ryw_read","msg_id":2,"key":"x","last_write_index":5,"prefer_follower":true}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
Follower behind redirects to leaderTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1","n2","n3"]}}
{"src":"c1","dest":"n1","body":{"type":"ryw_read","msg_id":2,"key":"x","last_write_index":999,"prefer_follower":true}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
Hints
Hint 1▾
Clients send their last-seen commit_index with each read request
Hint 2▾
Followers only serve the read if they have applied at least that index
Hint 3▾
If the follower is behind, it either waits or redirects to the leader
Hint 4▾
This combines the scalability of follower reads with read-your-writes guarantee
Hint 5▾
The client tracks the commit_index from write responses
OVERVIEW
Theoretical Hub
Concept overview coming soon
Key Concepts
read-your-writessession consistencycommit index trackingclient token
main.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python3
import sys
import json
def main():
# Your implementation here
for line in sys.stdin:
msg = json.loads(line)
print(json.dumps(msg), flush=True)
if __name__ == "__main__":
main()