Write Path Internals: InnoDB, Cache Consistency, and TLS
System DesignModel answerLast updated
Trace a single HTTPS profile update through TLS negotiation, a Redis cache-aside layer, and InnoDB's WAL-based durability guarantees.
The Long Road of a Single Write
A user submits a profile update on a high-traffic platform. The request travels through a load balancer, hits an application server backed by a Redis cache, and lands in a MySQL InnoDB database. Your job is to explain what actually happens at each layer — not at the level of "data goes in, data comes out," but at the level of what guarantees are being made and what can go wrong.
Answer the three sections below. Concrete mechanisms and trade-offs matter more than definitions.
Part 1 — Storage Durability
Trace what InnoDB does internally when the application executes:
UPDATE users SET display_name = 'Alice' WHERE id = 42;
COMMIT;
Specifically, walk through the roles of the Buffer Pool, the Redo Log (WAL), and the Undo Log. Explain why the committed change survives a process crash that happens the instant after the client receives the success response.
Also compare the durability and performance implications of setting innodb_flush_log_at_trx_commit to 1 versus 2.
Part 2 — Cache Consistency
The service uses a cache-aside (lazy-loading) pattern with Redis. The standard write sequence is:
- Write the new value to the database.
- Delete the cache key.
Describe a concrete race condition in which a concurrent read repopulates the cache with a stale value after the delete has already run. Then propose at least two strategies that reduce or eliminate this inconsistency window, and explain the trade-offs of each.
Why is a simple cache.delete() after a database commit not fully thread-safe, even when executed correctly?
Part 3 — Secure Request Lifecycle
Walk through the complete lifecycle of the HTTPS POST request, from the moment the client opens a connection to the moment the server sends back 200 OK. Cover:
- The TCP 3-way handshake and what it establishes
- The TLS 1.3 handshake: what each side sends, how the session key is derived, and what role the server certificate plays
- How the server signals whether the connection will be kept alive for future requests
Where relevant, call out how TLS 1.3 differs from TLS 1.2 in terms of round trips and forward secrecy.
What a strong answer looks like
- Part 1: a step-by-step trace that names specific InnoDB structures, explains crash recovery in three phases, and gives a concrete recommendation on the flush setting with justification.
- Part 2: a timeline that shows the exact interleaving that produces a stale cache hit, at least two mitigation strategies with trade-offs, and a short code sketch of the safest practical approach.
- Part 3: a sequential walkthrough that distinguishes authentication from key exchange, states the RTT cost of each phase, and notes what
Keep-Alive/Connection: keep-aliveheaders communicate.
Hints
Hint 1
For Part 1, ask yourself: what exactly has been written to durable storage at the moment the client sees 'commit successful'? The data page in the Buffer Pool is almost certainly still dirty — so what is guaranteeing durability?
Hint 2
For Part 2, draw out a timeline with two threads. The stale-repopulation race requires the read thread to fetch from the DB *before* the write commits but to write to the cache *after* the delete. That ordering is the key insight — then ask what tools can prevent or bound it.
Hint 3
For Part 3, separate the two jobs TLS has to do: prove the server is who it claims to be, and agree on a secret no eavesdropper can recover. In TLS 1.3 these are handled by different mechanisms — the certificate handles the first, ECDHE handles the second. Keep-Alive is an HTTP-layer concern layered on top of the already-established TLS connection.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Answer in request-path order: network first, then cache, then storage. The interviewer is testing whether you can follow one operation through every layer and identify failure modes at each boundary — not whether you can recite definitions.
Part 1 — InnoDB Durability
InnoDB never synchronously overwrites data pages on disk during a write. Instead it relies on write-ahead logging: the change is first recorded in a sequential log, and the data page is flushed to disk lazily in the background. Here is the step-by-step trace for the UPDATE above.
1. Locate the page and take a lock.
InnoDB checks the Buffer Pool for the B+tree leaf page containing id = 42. If it is not there, it reads it from disk. An exclusive row lock is taken. This is the foundation of Isolation.
2. Write the undo record.
Before modifying anything, InnoDB copies the old row version into an undo log segment. The row's hidden DB_ROLL_PTR pointer is updated to point to this record. Undo serves two purposes: rollback (Atomicity) and MVCC so concurrent readers can still see a consistent snapshot of the old value.
3. Modify the Buffer Pool page. The row is updated in memory. The page is now dirty — inconsistent with what is on disk.
4. Append redo records. Physical redo log records ("page X, offset Y, new bytes Z") are added to the in-memory redo log buffer. The modification to the undo page is also redo-logged, so undo survives a crash too.
5. Commit. InnoDB uses an internal two-phase commit with the binary log:
- Flush and fsync the redo log up to a prepare mark.
- Write and fsync the binlog event (
sync_binlog=1). - Write a commit mark to the redo log.
The client receives success only after the redo fsync in step 5. The dirty data page has almost certainly not reached disk yet — but it does not need to.
Crash recovery in three phases:
- Redo replay. InnoDB scans the redo log from the last checkpoint LSN and re-applies every logged change. This brings all pages to their final logged state, including committed writes whose dirty pages had not flushed.
- Undo pass. Any transaction with no commit record in the redo log is rolled back using the undo segments.
- Prepared transaction resolution. A transaction left in the prepare state is committed if its binlog event exists (so replicas are consistent), and rolled back otherwise.
This is why the commit survives an immediate crash: the redo record is on durable storage before the client is told to proceed.
innodb_flush_log_at_trx_commit trade-off:
| Setting | Flush behavior | Survives OS crash/power loss | Relative throughput |
|---|---|---|---|
1 | write + fsync on every commit | Yes — full Durability | Lower; group commit amortizes cost |
2 | write to OS page cache on commit, fsync ~every 1s | No — up to ~1s of commits lost | Significantly higher |
0 | buffer only, write + fsync ~every 1s | No | Fastest |
For any write where losing data is unacceptable (financial transactions, profile updates with downstream side-effects), use 1 paired with sync_binlog=1. Setting 2 is reasonable for read replicas or for data you can reconstruct, and it can increase throughput by an order of magnitude under write-heavy load.
Part 2 — Cache Consistency
The race condition with delete-after-write:
Even with the correct pattern (update DB → delete cache key), this interleaving is possible:
t1 Thread A (reader): cache miss on user:42
t2 Thread A: SELECT → reads old value v1 from DB
t3 Thread B (writer): UPDATE → v2, COMMIT
t4 Thread B: DEL user:42 ← key gone
t5 Thread A: SET user:42 = v1 ← stale value back in cache
Thread A's read started before the write, but its cache SET landed after Thread B's delete. The cache now holds a stale value until TTL expiry.
Why cache.delete() is not fully thread-safe:
Beyond the race above, there are two additional failure modes:
- The delete can fail or time out, leaving the stale key permanently.
- If the application uses read replicas, Thread A in step t2 might read from a lagging replica even after Thread B's commit, then fill the cache with that replica's stale version after the delete.
Mitigation strategies:
1. Delayed double-delete. Delete immediately after commit, then delete again after a delay slightly longer than the maximum read-path latency plus replica lag (say 300–500 ms). The second delete evicts any stale value refilled by an in-flight reader.
Trade-off: Simple to implement. Still has a short inconsistency window equal to the delay, and relies on an in-process timer (or better, a queue) that must survive restarts.
2. CDC-driven invalidation (binlog tailing). A change-data-capture consumer (Debezium, Canal) tails the MySQL binlog and deletes cache keys when it sees a committed row change. Invalidation is decoupled from the request path and retried until it succeeds via a message queue.
Trade-off: Adds operational complexity (a CDC pipeline, a queue). Introduces a small lag between commit and invalidation equal to replication lag to the CDC consumer — but this is typically well under a second and far more reliable than fire-and-forget deletes in application code.
3. Always set a TTL. This bounds the maximum staleness even when all other mechanisms fail.
Trade-off: Does not eliminate inconsistency, only caps it. Does not help for data that must be fresh (e.g., inventory counts).
Practical implementation of delayed double-delete:
import threading
SECOND_DELETE_DELAY_SEC = 0.5 # tuned to > read latency + replica lag
def update_profile(db, cache, user_id: int, name: str) -> None:
key = f"user:{user_id}"
with db.transaction() as tx:
tx.execute(
"UPDATE users SET display_name = %s WHERE id = %s",
(name, user_id),
)
# First delete: evict after commit
_safe_delete(cache, key)
# Second delete: evict stale values refilled by in-flight readers.
# In production, publish to a delayed queue rather than using a timer,
# so this survives process restarts.
threading.Timer(
SECOND_DELETE_DELAY_SEC,
lambda: _safe_delete(cache, key),
).start()
def _safe_delete(cache, key: str) -> None:
try:
cache.delete(key)
except Exception:
enqueue_retry_delete(key) # queue-backed retry until success
def enqueue_retry_delete(key: str) -> None:
... # publish to a message queue; consumer retries with backoff
A common mistake is to set the cache to the new value instead of deleting it. Under concurrent writes, two SET calls can land out of order, leaving the earlier value in cache. Delete is always safer than overwrite.
Part 3 — HTTPS Request Lifecycle
Step 1 — DNS. The client resolves the domain to the load balancer's IP (1 UDP round trip, often cached).
Step 2 — TCP 3-way handshake (1 RTT).
- Client → Server:
SYNwith a randomly chosen sequence number. - Server → Client:
SYN-ACKwith the server's sequence number, acknowledging the client's. - Client → Server:
ACK.
This establishes a reliable, ordered byte stream and synchronizes sequence numbers. Nothing application-level has moved yet.
Step 3 — TLS 1.3 handshake (1 RTT).
- ClientHello: client random, supported cipher suites, an ECDHE key share (public half), SNI (the hostname, in plaintext), and ALPN extension listing preferred protocols (
h2,http/1.1). - ServerHello: server random, selected cipher suite, and the server's ECDHE key share.
- Both sides now have enough material to compute a shared secret via ECDHE. HKDF over that secret and the handshake transcript derives symmetric session keys (typically AES-256-GCM).
- The server sends Certificate (its X.509 cert chain), CertificateVerify (a signature over the handshake transcript, proving it holds the matching private key), and Finished (an HMAC of the transcript with the derived key).
- The client verifies the cert chain against trusted CAs, checks the hostname matches, verifies the CertificateVerify signature, then sends its own Finished.
Two points worth emphasizing: the server's certificate key authenticates the server's identity; it does not encrypt the session key. The session key comes entirely from the ECDHE exchange, which means every session gets a fresh secret — this is forward secrecy. In TLS 1.2 with RSA key exchange, the session key was encrypted with the server's certificate public key, so compromising the certificate later could decrypt all past traffic. TLS 1.2 with ECDHE fixes this but costs 2 RTT; TLS 1.3 collapses it to 1 RTT by sending the key share in the first message.
Step 4 — HTTP request and response.
The application layer sends the POST /profile request over the encrypted channel. The server processes it (through the cache and database path described above) and returns HTTP/1.1 200 OK or HTTP/2 200.
Step 5 — Keep-Alive.
For HTTP/1.1, the server includes Connection: keep-alive to signal that the underlying TCP (and TLS) connection should remain open for subsequent requests, avoiding the cost of repeating steps 2–3. The client can send the next request immediately without a new handshake. HTTP/2 multiplexes all requests over a single connection by design, so Keep-Alive is implicit.
Common mistakes to avoid:
- Saying TLS encrypts with the certificate's public key — that is RSA key exchange (deprecated in TLS 1.3).
- Conflating the TCP handshake with the TLS handshake — they are sequential, not overlapping.
- Forgetting that HTTP Keep-Alive is a separate, application-layer concern from the persistent TCP connection TLS runs over.