Scrivio Interview library
DebuggingIntermediate6 min read · updated 13 November 2026

A SaaS platform uses directory sharding: a tenant_shard table maps each tenant to a PostgreSQL shard, and every pod caches the table for 60 seconds. After an operator moved tenant 4411 from shard 3 to shard 7, support found new orders that exist only on the old shard.

Explain how writes reached the old shard after the move, and how you would change the directory and the move procedure so it cannot happen again.

Pods that had cached the old mapping kept routing tenant 4411 to shard 3 for up to 60 seconds after the switch, and shard 3 accepted the writes because nothing on it knew it no longer owned the tenant. The fix is to make each shard enforce ownership with an epoch, run moves as a fenced protocol (MOVING, drain, final catch-up, switch with a new epoch, unblock), push invalidations so caches refresh in seconds, and repair this incident by replaying the orphaned writes to shard 7.

Why this question is asked

Directory sharding is flexible: any tenant can move to any shard by changing one row. But the directory is only as correct as the oldest copy of it, and every pod keeps a copy. Interviewers ask this debugging scenario because it shows the core lesson of moving data between shards: routing tables are hints, and correctness must be enforced by the shard that holds the data. In this answer, we will reconstruct how the writes reached the old shard, make the shards check ownership, turn the move into a protocol, speed up invalidation, and repair the data from this incident.

1A Quick Recap: Directory Sharding and Its Caches

In directory sharding, a table, here tenant_shard, records which shard each tenant lives on. Every request looks up its tenant and goes to the listed shard. Reading the directory for every request would be slow and would make it a bottleneck, so each pod caches the whole table and reloads it every 60 seconds. That cache is the heart of the problem: during those 60 seconds, a pod's view of the world can be wrong.

2How the Writes Reached the Old Shard

The operator copied tenant 4411's data from shard 3 to shard 7 and then updated the directory row to point to shard 7. Some pods reloaded their cache a second later; others had reloaded just before the change and kept the old mapping for almost a full minute. Those pods kept sending tenant 4411's new orders to shard 3. And shard 3 accepted them, because a PostgreSQL shard has no idea about the directory; tenant 4411's tables are still there, and an INSERT is valid. So for up to 60 seconds, orders were written to shard 3, which nobody reads anymore. Shard 7, where the tenant now lives, never saw them.

Step throughThe stale cache window
OperatorDirectoryPod with old cacheShard 3Shard 7
copy tenant 4411 data
set tenant 4411 -> shard 7
INSERT order (cache still says shard 3)
OK: nothing on shard 3 knows the tenant moved
cache reload, up to 60 s later
later orders go to shard 7

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

The router was stale, and the shard had no way to refuse.

3Fix 1: Make Each Shard Enforce Ownership

The durable fix is to stop trusting the router alone. Each shard keeps its own record of the tenants it owns, with an epoch: a number that increases every time ownership of that tenant changes. The router sends the epoch it believes in along with each transaction, and the shard checks it before writing. If the tenant is not owned here, or the epoch is older than the one the shard knows, the write fails with a clear, specific error, and the pod refreshes its directory and retries on the correct shard.

Java
-- on every shard
CREATE TABLE tenant_ownership (
tenant_id bigint PRIMARY KEY,
epoch bigint NOT NULL,
state text NOT NULL CHECK (state IN ('OWNED', 'MOVING', 'GONE'))
);
-- at the start of each write transaction, from the routing layer
SET LOCAL app.tenant_id = '4411';
SET LOCAL app.epoch = '12';
-- a trigger function on tenant tables (sketch)
CREATE FUNCTION check_owner() RETURNS trigger AS $$
BEGIN
PERFORM 1 FROM tenant_ownership
WHERE tenant_id = NEW.tenant_id AND state = 'OWNED'
AND epoch = current_setting('app.epoch')::bigint;
IF NOT FOUND THEN
RAISE EXCEPTION 'tenant % not owned here at this epoch', NEW.tenant_id USING ERRCODE = 'P0001';
END IF;
RETURN NEW;
END $$ LANGUAGE plpgsql;
-- after the move, on shard 3: state = 'GONE' -> a stale pod's INSERT fails instead of succeeding

A trigger is one way; an alternative is to have the routing layer run a guarded statement such as SELECT ... FROM tenant_ownership ... FOR SHARE at the start of each transaction and abort if it returns nothing. The row lock also matters for the move: a transaction holding a shared lock on the ownership row blocks the move's exclusive update until it finishes, so no write can slip in during the switch.

4Fix 2: Run Every Move as a Protocol

Copying data and flipping a row is not a move; it is a race. A safe move follows fixed steps, and the important ones are in the middle, where writes are fenced.

Step throughA fenced tenant move
  1. Copy and stream changes to shard 7bulk copy plus change capture while live
  2. Mark tenant MOVING in directory and on shard 3shard 3 now rejects new writes for 4411
  3. Wait for in-flight transactions to endthey hold the ownership row lock
  4. Apply the final changes to shard 7up to the source's last position
  5. Switch the directory, epoch 12 -> 13shard 7 OWNED at 13, shard 3 GONE
  6. Unblock and notify podsretried writes now reach shard 7

6 steps in order. Play them, or step through them one at a time.

The write pause lasts from step 2 to step 6, usually a second or two for one tenant. During it, writes for tenant 4411 get a retryable error, which clients retry with a short backoff. Every other tenant is unaffected.

5Fix 3: Push Invalidations, Keep the TTL as a Safety Net

With ownership enforced, stale caches can no longer cause lost writes, but they still cause failed requests and retries until they refresh. So we shorten the stale window. When the directory changes, the change is published, for example through PostgreSQL LISTEN/NOTIFY on the directory database, a Redis pub/sub channel or a Kafka topic, and every pod updates its cache within a second or two. A pod can also refresh immediately when a shard rejects a write with the ownership error. The 60-second TTL stays, but only as a safety net for a missed notification.

6Repairing This Incident

For the orders already written to shard 3, we first stop the bleeding: mark tenant 4411 as read-only or GONE on shard 3 so no more writes land there. Then we find the window, from the moment of the switch until the last pod refreshed, with some margin. We compare tenant 4411's rows on both shards for that window by primary key and updated_at. Rows that exist only on shard 3 are replayed to shard 7 in commit order; rows that exist on both but differ need care, because something may have been changed on shard 7 since, so those are compared field by field and decided with the business. Any customer-visible effects, such as order confirmations sent for orders now invisible, are checked too. Only after shard 7 is verified is the old copy deleted.

7Follow-up questions

Where would you keep the directory so it does not become a single point of failure?

In a small, replicated, strongly consistent store, for example a PostgreSQL cluster with synchronous replicas or a consensus-based store such as etcd, with every pod holding a full cached copy. Because reads come from the cache, a short outage of the directory store only blocks moves and cache refreshes, not normal traffic. Changes to the directory go through one writer, the move orchestrator, so epochs increase cleanly.

Why use an epoch rather than just a flag saying the tenant moved?

Because a tenant can move more than once. An epoch lets a shard reject a request based on a map that is any number of moves out of date, and it makes the directory switch and the ownership change one comparable value rather than several flags that could disagree.

Is a shorter TTL, such as 5 seconds, enough on its own?

No. It shrinks the window but never closes it, and it multiplies directory reads. Only enforcement at the shard makes stale routing safe; invalidation just makes it rare.

8Conclusion

In this answer, we saw that pods with a cached directory kept routing tenant 4411 to shard 3 for up to 60 seconds, and shard 3 accepted the writes because it did not know it no longer owned the tenant. The fix makes each shard enforce ownership with an epoch, runs moves as a fenced protocol that marks the tenant MOVING, drains in-flight work, catches up, switches with a new epoch and unblocks, and pushes invalidations so caches refresh quickly with the TTL as a safety net. The incident itself is repaired by diffing the window on both shards and replaying the orphaned writes to shard 7.

What to say in the interviewAbout 90 seconds aloud

Open with

The directory changed, but the routers did not all know it yet. Every pod caches tenant_shard for 60 seconds, so pods that had loaded it just before the switch kept sending tenant 4411 to shard 3 for up to a minute.

Then, if they want more

And shard 3 happily accepted those writes, because nothing on it knew it no longer owned the tenant; the tables were still there. So the fix has to be on the shard.

Each shard keeps an ownership table with the tenant, its state and an epoch, and every write checks it, through the routing context plus a trigger or a guarded select with a shared lock. A stale router then gets a clear error, refreshes its map and retries on the right shard.

Then the move itself becomes a protocol: copy and stream changes, mark the tenant MOVING on the directory and the source so new writes are rejected, let in-flight transactions finish, apply the final changes to the target, switch the directory with a new epoch, and unblock.

I would also push invalidations through pub/sub or a change feed so pods refresh in seconds, with the TTL only as a safety net. For the incident, I would freeze tenant 4411 on shard 3, diff its rows on both shards for the window, replay the missing writes to shard 7 in order, and only then delete the old copy.

About this answer

Last updated
13 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 official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "Explain how writes reached the old shard after the move, and how you would change the...": https://scrivio-interview-library.netlify.app/architecture/partitioning-and-replication/d3a741099a/