Sub topic 11
Session guarantees: read-your-writes, monotonic reads and more
This chapter assumes you know what replication is and how an eventually consistent store can return stale reads. It also assumes you can read short Python programs. Session guarantees are a small set of promises that make an eventually consistent store feel sensible to one client, without paying for linearizability.
The problem they solve
In an eventually consistent store, replicas converge once writes stop. Until then, a client talking to different replicas can see odd behavior:
- You post a comment, refresh, and the comment is gone.
- You see a new value, refresh, and see the old value again.
- You reply to a message that other readers then see before the message itself.
Each of these is legal under plain eventual consistency. None of them is a violation of convergence. They are violations of what a single user expects from their own sequence of operations.
A session is a sequence of reads and writes issued by one client (a user, a browser tab, or an application thread) that the system treats as related. A session guarantee is a promise about what that sequence will observe. The promise concerns only that session. It says nothing about what other clients see, which is why it is far cheaper than a global guarantee.
The four guarantees
These four were defined in the Bayou system at Xerox PARC (Terry et al., 1994).
| Guarantee | Promise | Anomaly it prevents |
|---|---|---|
| Read-your-writes | A read sees all earlier writes from the same session. | Saving a profile, then seeing the old profile. |
| Monotonic reads | A read never returns older data than an earlier read in the same session. | Values appearing to move backward in time. |
| Monotonic writes | A session's writes are applied in the order the session issued them. | Write 2 surviving while write 1 is lost or applied later and overwrites it. |
| Writes-follow-reads | A write is ordered after the writes whose results the session has read. | A reply becoming visible before the message it answers. |
The first two constrain what a session reads. Monotonic writes constrains how a session's writes are ordered. Writes-follow-reads constrains how a write is ordered relative to what the session read before issuing it.
How the guarantees compose
Each guarantee covers one slice of the causal ordering. Together, all four are equivalent to causal consistency for a session (Brzezinski et al., 2004). That is why the spine places session guarantees after causal consistency: they are the pieces you can offer separately, often at a lower cost.
You do not have to provide all four. A shopping cart might need only read-your-writes. A dashboard that polls a counter might need only monotonic reads, so the number never goes down.
A failure and its fix
The diagram shows a read-your-writes violation. The client's write goes to the primary. The next read goes to a replica that has not yet received the write.
The fix is to make the client remember how far it has progressed and refuse answers that are behind that point.
Implementing the guarantees
Most implementations use the same technique. Each write gets a version (a number, a timestamp, or a vector clock). The client session keeps a floor: the highest version it has written or read for each key. A replica may answer a read only if its version is at or above the floor. Otherwise the client tries another replica, waits, or falls back to the primary.
class Replica:
def __init__(self, name):
self.name = name
self.data = {} # key -> (version, value)
def apply(self, key, version, value):
"""Apply a replicated write, ignoring anything older than what we hold."""
if key not in self.data or self.data[key][0] < version:
self.data[key] = (version, value)
class Primary(Replica):
def write(self, key, value):
version = self.data.get(key, (0, None))[0] + 1
self.data[key] = (version, value)
return version
class Session:
def __init__(self, primary, replicas):
self.primary = primary
self.replicas = replicas
self.floor = {} # key -> highest version this session has seen
def write(self, key, value):
version = self.primary.write(key, value)
self.floor[key] = max(self.floor.get(key, 0), version)
return version
def read(self, key, prefer=None):
order = ([prefer] if prefer else []) + self.replicas + [self.primary]
for replica in order:
entry = replica.data.get(key)
if entry and entry[0] >= self.floor.get(key, 0):
self.floor[key] = entry[0]
return entry[1]
raise RuntimeError("no replica is fresh enough")
primary = Primary("primary")
r1, r2 = Replica("r1"), Replica("r2")
alice = Session(primary, [r1, r2])
alice.write("x", "a") # version 1, replicas have not received it
print(alice.read("x", prefer=r1)) # a (r1 is behind, so the primary answers)
r1.apply("x", 1, "a")
v = primary.write("x", "b") # another client writes version 2
r2.apply("x", v, "b") # only r2 has received it so far
print(alice.read("x", prefer=r2)) # b (floor is now 2)
print(alice.read("x", prefer=r1)) # b (r1 holds version 1, below the floor)One floor per key enforces both read-your-writes (the write raises the floor) and monotonic reads (each read raises it). Without the floor, the last read would have returned a from r1, and the value would have gone backward.
Real systems pass the floor in different forms:
- Session tokens. The server returns an opaque token with each response. The client sends it back on the next request. Azure Cosmos DB's session consistency level works this way.
- Sticky sessions. A load balancer pins a client to one replica. This is simple, and it gives read-your-writes and monotonic reads while that replica lives.
- Read from the primary after a write. For a short window after a write, route that user's reads to the primary. Many web applications with replicated SQL databases do this.
- Wait for a log position. The client records the log sequence number of its write and waits until the replica has replayed past it.
Monotonic writes and writes-follow-reads
These two are less commonly needed, but the failures are severe.
For monotonic writes, a replica must not apply a session's second write before its first. The usual mechanism is to send a session's writes through one ordered channel, or to attach a per-session sequence number and have replicas buffer out-of-order arrivals. With last-write-wins on a single key, a late write 1 can overwrite write 2 if timestamps are assigned at arrival.
For writes-follow-reads, a write must carry the dependency information of what the session read. A reply stores the version of the message it answers, and a replica delays making the reply visible until it holds that message. This is the same dependency tracking that causal consistency uses, so a vector clock is the usual tool.
Edge cases and common errors
- Failover loses the guarantee. Sticky sessions break when the pinned replica dies. If the new replica is behind, the client may see its writes vanish. A session token survives failover. Pinning does not.
- Different devices are different sessions. A write on a phone and a read on a laptop share no floor unless the token is stored server-side, keyed by user.
- Session scope is your decision. If each HTTP request creates a new session, you provide no guarantee at all. Decide what a session is, and persist its state for as long as the guarantee must last.
- Tokens cost availability. If no replica reaches the floor, the read must block, retry, or fail. Under a partition, you choose between a stale answer and no answer, which is the CAP trade-off applied to one session.
- Reading your own write from a different key. A floor per key does not cover cross-key relationships. A client that writes
profileand then readsprofile_summarymay still see stale data, unless the floor is a store-wide position such as a log sequence number. - Do not confuse these with linearizability. After Alice's write completes, Bob may still read the old value. Only Alice is protected.
Exercise
A user updates their display name in a mobile app, and the app immediately reloads the profile screen. Reads are served by any of three asynchronously updated replicas, and the app sometimes shows the old name. Which session guarantee is violated, and name two ways to fix it without making the whole store linearizable.
Show answer
Read-your-writes is violated. The write went to one node, and the following read went to a replica that had not yet received it. Fixes: (1) return a session token or write version with the write response, send it with later reads, and have a replica answer only if it has reached that version (otherwise try another replica or the primary); (2) route the user's reads to the primary for a short window after a write. Pinning the user to one replica also helps but breaks on failover.
Exercise
A session reads x = 5 from replica A, then its next read goes to replica B, which still holds x = 3. Which guarantee does this violate, and what does the session need to remember to prevent it?
Show answer
Monotonic reads. The session must remember the highest version of x it has read (the floor, here the version that held 5) and reject any replica answer below it.