How to Mock Sticky Session Read-Your-Writes in Python
Simulates a sticky session store that routes reads for a session to the node where the last write occurred, demonstrating read-your-writes consistency.
Python code
20 linesclass StickySessionStore:
def __init__(self):
self.data = {}
self.session_nodes = {}
def write(self, session_id, key, value):
self.data[key] = value
self.session_nodes[session_id] = key
return f"Wrote {key}={value} for session {session_id}"
def read(self, session_id, key):
if self.session_nodes.get(session_id) == key:
return f"Read {key}={self.data.get(key)} from sticky node"
return f"Read {key}={self.data.get(key)} from non-sticky node"
if __name__ == "__main__":
store = StickySessionStore()
print(store.write("s1", "name", "Alice"))
print(store.read("s1", "name"))
print(store.read("s2", "name"))
Output
Wrote name=Alice for session s1
Read name=Alice from sticky node
Read name=Alice from non-sticky node
How it works
The StickySessionStore keeps a session_nodes dict that maps each session ID to the key of its most recent write. When a read occurs, the code checks whether the session's last written key matches the requested key; if so, it simulates a read from the sticky node (the node that served the write), otherwise it simulates a non-sticky read. This models the read-your-writes consistency guarantee provided by sticky sessions in load-balanced systems. The mock is useful for testing application logic that depends on session affinity without spinning up a real database or cluster.
Common mistakes
- Forgetting that a session can write multiple keys, so a single session-to-node map isn't enough.
- Assuming all reads for a session are sticky, when only the latest write is sticky.
- Not handling edge cases where no write has occurred for the session before a read.
Variations
- Use a dict of session_id to node_id instead of key, requiring an additional key-to-node lookup.
- Add a time-based expiry to simulate session timeouts.
Real-world use cases
- Testing web application logic that relies on session affinity to maintain user session state.
- Simulating read-your-writes behavior in a mock for database replication testing.
- Prototyping load balancer routing rules before implementing with real infrastructure.
Sponsored
More from Database scaling & optimization
- Approximate Count with HyperLogLog in Python medium
- B-Tree Insert and In-Order Traversal in Python hard
- Broadcast a Small Reference Table in Python easy
- Build a Full Text Search Index in Python medium
- Build a Partial Index Mock in Python for Database Filtering easy
- Composite index leftmost prefix in Python medium
Keep learning
Related tutorials and quizzes for this topic.