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.

Easy Python 3.9+ Aug 9, 2026 Database scaling & optimization 13 views 0 copies

Python code

20 lines
Python 3.9+
class 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

stdout
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

  1. Use a dict of session_id to node_id instead of key, requiring an additional key-to-node lookup.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Database scaling & optimization

Related tutorials and quizzes for this topic.