Middle · Trace · Invalidate cached reads after a successful commit

Portable .NET9 console only: predict every printed line and explain why the rejected candidate leaves rune cached and the accepted source change produces exactly two reads. State which real HTTP, SQL or infrastructure guarantee this program does not test.

Think through your answer before opening the explanation.

Production engineering

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

string source="rune"; string? cached=null; int reads=0; string Read() { if(cached is null) { reads++; cached=source; } return cached; }
Console.WriteLine(Read()); string rejectedCandidate="unused"; _=rejectedCandidate; Console.WriteLine(Read()); source="glyph"; cached=null; Console.WriteLine(Read()); Console.WriteLine("reads:"+reads);
Reveal answer and reasoning

The first Read sees no cached value, increments reads and caches rune, so it prints rune. The rejected candidate is merely a local unused draft and never replaces source, so the next Read still prints rune without another source read. Assigning glyph to source and explicitly clearing cached makes the following Read print glyph. The final count is reads:2. No rollback, HybridCache call or concurrent reader exists in the console.

It explains which source change was accepted and when its one owner invalidated a snapshot, not how a network cache coordinates with a database.

The actual first catalog read returns rune at version one and records one source factory read. A failed SQL write rolls back, after which the cached value and read count remain unchanged. A valid glyph update commits version two, then awaits removal of catalog:1. The next read obtains glyph/version two and increments source reads to two. These checks distinguish return value, persistence and cache activity rather than accepting a successful status alone.

They do not force an invalidation outage, concurrent refill race or second HybridCache instance; those remain separate scenarios with different evidence requirements.

What a strong answer covers

  • The companion prints rune,rune,glyph and reads2 without executing SQL or HybridCache.
  • Actual pre-commit rollback preserves source/version1 and the valid cached entry.
  • Commit then removal remains two fallible boundaries; cross-instance coordination is not configured.

Common pitfall

Calling database commit plus a later cache removal one atomic distributed transaction.

Follow-up questions

  1. What should happen if the write committed but cache removal failed?
  2. How would another process discover or expire its stale entry?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions