Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

Users update their profile and immediately reload the page, but sometimes see the old data. The service reads with readPreference secondaryPreferred. Explain and fix it without sending all reads to the primary.

Secondaries replicate asynchronously, so a read sent to a secondary right after a write can reach one that has not applied that write yet, and the user sees their old profile. Without sending every read to the primary, we can use causally consistent sessions with majority read and write concern, carrying the session's operation time from the write request to the next read so the secondary waits until it has caught up, or route only the user's own data to the primary for a short time after they write while other reads stay on secondaries. maxStalenessSeconds only limits how far behind a chosen secondary may be and does not guarantee read-your-writes, and we should measure replication lag and alert on it.

Why this question is asked

Read-your-writes is one of those guarantees users assume without knowing the name. If I change my display name and reload, I expect to see the new one. With secondaryPreferred, MongoDB happily serves that reload from a secondary that is a few hundred milliseconds behind, and the user thinks the save failed and tries again. Interviewers ask this because it tests understanding of replication lag and of the specific tools MongoDB offers, and whether we can fix one user's experience without throwing away the read scaling that secondaries provide. In this answer, we will recap why the stale read happens, look at causal consistency and how to carry it across HTTP requests, consider routing a user's own reads to the primary for a short window, see why maxStalenessSeconds is not the answer, and finish with lag monitoring.

1A Quick Recap: Why the Old Data Appears

In a replica set, the primary applies a write and acknowledges it; secondaries then copy it from the oplog and apply it a little later. That delay is replication lag, usually milliseconds, but it can reach seconds under heavy load, during index builds, or on an overloaded secondary. readPreference secondaryPreferred sends reads to a secondary whenever one is available.

So the profile update goes to the primary and succeeds, and the reload, a separate request, goes to a secondary. If that secondary has not yet applied the update, it returns the previous version. Nothing is broken; the system is doing exactly what we configured, which is to trade freshness for read capacity.

Step throughA stale read after a profile update
BrowserServicePrimarySecondary
save name = 'Ana S.'
update profile, w:majority
ok
reload profile
find profile, secondaryPreferred
name = 'Ana' (not yet applied)
replicates the update 300 ms later

7 messages in order. Play them, or step through them one at a time.

The write is safe; the read simply reached a member that had not caught up.

2Fix 1: Causally Consistent Sessions

MongoDB supports causal consistency within a client session. In a causally consistent session, every operation records the cluster time at which it happened, and later reads in the same session tell the server 'do not answer until you have applied everything up to this time'. A secondary that is behind waits until it catches up, then answers. To make the guarantee hold even through failovers, the session's writes use w:'majority' and its reads use read concern 'majority'.

Java
ClientSession session = client.startSession(
ClientSessionOptions.builder().causallyConsistent(true).build());
MongoCollection<Document> profiles = db.getCollection("profiles")
.withWriteConcern(WriteConcern.MAJORITY)
.withReadConcern(ReadConcern.MAJORITY)
.withReadPreference(ReadPreference.secondaryPreferred());
profiles.updateOne(session, eq("_id", userId), set("name", "Ana S."));
Document p = profiles.find(session, eq("_id", userId)).first();
// p.name == "Ana S." even if served by a secondary
// after the write
BsonTimestamp opTime = session.getOperationTime();
BsonDocument clusterTime = session.getClusterTime();
httpSession.setAttribute("mongoOpTime", opTime);
httpSession.setAttribute("mongoClusterTime", clusterTime);
// on the next request
ClientSession next = client.startSession(
ClientSessionOptions.builder().causallyConsistent(true).build());
next.advanceClusterTime((BsonDocument) httpSession.getAttribute("mongoClusterTime"));
next.advanceOperationTime((BsonTimestamp) httpSession.getAttribute("mongoOpTime"));
Document fresh = profiles.find(next, eq("_id", userId)).first(); // waits for the secondary to catch up

Notice the catch for a web application: the reload is a new HTTP request, and probably a new session, possibly on a different server instance. The guarantee only applies to operations in the same causal chain. So after the write we save the session's operationTime and clusterTime, for example in the user's server-side HTTP session, and at the start of the next request we create a new session and advance it to those times.

The cost is that a read may wait briefly for the secondary, so we keep a maxTimeMS on it and fall back to the primary if the wait is too long. The benefit is that all reads still go to secondaries.

3Fix 2: Read Your Own Data From the Primary, Briefly

A simpler, very common approach is to route by data and time. Reads of the current user's own data, for a short window after that user writes, go to the primary; everything else, such as other people's profiles, lists and search results, stays on secondaries. The window can be a few seconds, comfortably above normal lag.

Java
// after a successful write
httpSession.setAttribute("lastWriteAt", Instant.now());
// when reading the user's own profile
Instant last = (Instant) httpSession.getAttribute("lastWriteAt");
ReadPreference pref = (last != null && last.isAfter(Instant.now().minusSeconds(5)))
? ReadPreference.primary()
: ReadPreference.secondaryPreferred();
Document p = profiles.withReadPreference(pref).find(eq("_id", userId)).first();

Only a tiny fraction of reads go to the primary, those from users who just changed something, so the read scaling is almost unchanged. The approach is easy to reason about and needs no special driver features. Its weakness is that it relies on the window being longer than the lag, which is why we also monitor lag.

4Why maxStalenessSeconds Is Not Enough

maxStalenessSeconds is a read preference option that tells the driver not to choose a secondary estimated to be more than that many seconds behind the primary. Its minimum is 90 seconds, because staleness is estimated from periodic heartbeats and is not precise.

So it protects against very stale secondaries, for example one that fell minutes behind, but it does nothing for the scenario here. A secondary 300 milliseconds behind passes a 90-second staleness check easily and still returns the old profile. maxStalenessSeconds is a useful safety net for read quality in general, not a read-your-writes guarantee.

Options for read-your-writes
OptionReads stay on secondaries?GuaranteeCost
readPreference primary for allnoyesloses read scaling
Causal session, majority concernsyesyes, within the causal chaincarry op time across requests
Primary for own data after a writealmost allyes if window exceeds lagsmall routing logic
maxStalenessSecondsyesno, only bounds stalenessminimum 90 s, coarse

5Measure Replication Lag and Alert on It

Whatever fix we choose, replication lag is the number that decides how often users see stale data and whether a fixed time window is long enough. We measure it continuously with the replica set status or rs.printSecondaryReplicationInfo(), which shows how far each secondary is behind the primary, and we export it as a metric. We alert when lag exceeds, say, 2 seconds for more than a minute, because that usually means an overloaded secondary, a slow disk, a long-running index build or a network problem, and the secondary should be fixed or taken out of read rotation.

6Follow-up questions

Does causal consistency work with w:1?

Causal sessions work with any concerns, but the guarantees can be lost during a failover if writes are w:1 or reads are 'local', because those writes can be rolled back. For a guarantee that survives failover, use w:'majority' and read concern 'majority'.

Could we just use readPreference nearest?

nearest picks the member with the lowest latency, primary or secondary, so it has the same stale-read problem as secondaryPreferred. It is good for latency, not for freshness.

What about caching the new profile in the application after the write?

That can hide the problem for the page that did the write, but other instances and other pages still read stale data. It also creates a second source of truth. The database-level fixes are more reliable.

7Conclusion

In this answer, we saw that stale profile reads happen because secondaries apply writes after the primary, and secondaryPreferred sends the reload to one that has not caught up. We fixed it either with causally consistent sessions using majority read and write concern, carrying the operation and cluster time from the write to the next request, or by reading the user's own data from the primary for a short window after they write. maxStalenessSeconds, with its 90-second minimum, only bounds staleness and does not give read-your-writes, and replication lag must be measured and alerted on.

What to say in the interviewAbout 80 seconds aloud

Open with

The write goes to the primary and succeeds, but replication to secondaries is asynchronous, so when the user reloads, secondaryPreferred can send the read to a secondary that hasn't applied the update yet, maybe a few hundred milliseconds behind, and it returns the old profile.

Then, if they want more

I wouldn't send all reads to the primary; I'd give read-your-writes only where it's needed. One option is causal consistency: a causally consistent session with majority write and read concern means later reads in the session wait until the secondary has caught up to the session's operation time.

Because the reload is a separate HTTP request, I'd store the session's operationTime and clusterTime in the user's server-side session after the write, and advance a new session to them on the next request, with a maxTimeMS and a primary fallback.

The simpler option is routing: for a few seconds after a user writes, reads of that user's own data go to the primary, and everything else stays on secondaries, so read scaling is barely affected. I'd point out that maxStalenessSeconds doesn't solve this, because its minimum is ninety seconds and it only excludes very stale secondaries.

And I'd measure replication lag per secondary and alert on it, because lag decides how often this happens.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
MongoDB manual
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Users update their profile and immediately reload the page, but sometimes see the old...": https://scrivio-interview-library.netlify.app/databases/mongodb/9b60d6ea42/