Scrivio Interview library

Sharding, partitioning and replication

46 questions in 10 subtopics.

About this topic

Partitioning and replication are how data systems grow beyond one machine and survive the loss of one. Partitioning, or sharding, splits data so each node holds and serves a part of it; replication keeps copies on several nodes so reads scale and failures do not lose data. Both bring hard production problems: hot keys that saturate one shard, data moves that hurt latency, replicas that lag or drift, conflicting writes in several regions, and failovers that lose acknowledged commits. The questions cover range, hash and directory sharding, consistent hashing, rebalancing, skew, leader-follower, multi-leader and leaderless replication, quorums, replication lag and its consistency anomalies, conflict resolution with last write wins and CRDTs, and multi-region data, with real incidents, concrete numbers and the strategic decisions senior engineers own.

Range, hash and directory sharding

Sharding assigns every key to a partition by key range, by hash, or through a lookup directory. Range sharding keeps neighbouring keys together for scans but can concentrate new writes; hashing spreads load but loses range queries; a directory allows flexible placement at the cost of a lookup service. Understand how requests are routed, how routing information stays correct when data moves, and why the choice shapes ids and APIs for years.

InternalsFoundations6 min read

Range-partitioned stores, such as HBase, Bigtable-style systems and several distributed SQL databases, keep rows sorted by key and cut the key space into contiguous ranges that are spread across servers and split automatically as they grow.

How does such a store decide where a key lives, how does a range split happen, and how does a client find the right server after a split has moved data?
CodingFoundations8 min read

A team plans application-level sharding for a Spring Boot service: customer ids are hashed into 1,024 fixed logical buckets, and a small table maps each bucket to one of 8 physical PostgreSQL shards so buckets can later move between shards.

Write the core Java routing code that maps a customer id to a shard, and explain the choice of hash function, how negative hash values are handled, and how the bucket map is replaced safely while requests are running.
DebuggingIntermediate6 min read

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.
ScenarioAdvanced8 min read

A B2B platform shards by tenant through a directory, with one tenant never spanning shards. The largest enterprise tenant now fills 3.5 TB of a 4 TB volume on its dedicated shard, grows by about 150 GB a month and drives 70 percent of that shard's CPU at peak.

The directory cannot split a single tenant. What do you do in the next two months and in the long term, and how do you choose a second-level sharding key for this tenant?
LeadershipPrincipal7 min read

Some teams embed the shard number in every generated id, for example in the top bits of a 64-bit id, so any service can route without a lookup. Other teams keep ids opaque and route through a directory service.

As the senior technical leader setting the identifier and routing standard for the next ten years, which approach do you choose, and which long-term consequences do you weigh?

Consistent hashing and virtual nodes

Consistent hashing places nodes and keys on a ring so that adding or removing a node moves only a small share of keys. Virtual nodes give each machine many ring positions to even out load and spread recovery work. Understand how replicas are chosen around the ring, why few tokens cause imbalance, how bounded-load variants cap hot servers, and why every client must compute placement identically.

InternalsFoundations7 min read

In Dynamo-style stores such as Cassandra, each node owns several tokens, called virtual nodes, on a hash ring, and every key is stored on several replicas chosen by walking the ring from the key's position.

How are the replicas for a key chosen when nodes own many virtual nodes, why must the walk skip tokens of the same physical node and rack, and why do more tokens per node give a more even spread?
DebuggingIntermediate7 min read

A Cassandra cluster was created with num_tokens set to 4 and random token allocation, to make repairs cheaper. After three nodes were added, nodetool status shows effective ownership from 4 to 14 percent per node, and the 14 percent node has twice the disk use and read latency of the others.

Explain why so few tokens give such skewed ownership, how you would confirm it, and how you would fix it on a running cluster.
DesignIntermediate7 min read

A chat service routes each room to one of 20 WebSocket servers with consistent hashing, so all members of a room share in-memory state on one server. During evening peaks a few very busy rooms leave one server with 2.3 times the average number of connections while others sit idle.

Design a routing scheme that keeps room affinity but caps how far above average any server can go, and explain what happens when servers join or leave.
LeadershipPrincipal7 min read

About 300 services use a client-side sharded cache. After half of them upgraded the client library, the hit ratio fell from 94 to 60 percent and some services read stale prices: the new version hashes keys and names virtual nodes differently, so the two halves place keys on different servers.

As the senior technical leader, how do you recover, and what standard do you set for how services find the right cache or shard node in future?

Rebalancing and resharding

Rebalancing moves partitions between nodes when the cluster grows, shrinks or becomes uneven; resharding changes the partitioning itself. Systems differ in the units they move and whether moves are automatic. Understand what data moves in each approach, how copying competes with live traffic, and how a cutover is fenced so no write is lost, because most data loss in migrations happens at the switch.

ConceptFoundations7 min read

Partitioned databases must move data when nodes are added or removed. They differ in how they define the units of data that move and in when those units are created.

Compare three rebalancing approaches: a fixed number of partitions created up front, ranges that split and merge by size, and a fixed number of partitions per node. What moves when a node is added, and where does each approach fit?
DebuggingIntermediate7 min read

At 14:00 an operator added 4 nodes to a 12-node distributed database, and automatic rebalancing started to move about 9 TB. Within minutes p99 read latency rose from 8 ms to 140 ms, disks on the original nodes showed 100 percent utilisation and client timeouts began.

Explain why the rebalance hurt foreground traffic, how you would stop the damage, and how you would run the expansion safely, including the controls you expect such a database to offer.
ScenarioAdvanced8 min read

During an online split, bucket 412 was copied to a new shard and a change-capture stream reported the target caught up, after which routing was switched. A day later reconciliation found that about 0.3 percent of rows in the bucket lack updates committed in the two seconds before the switch.

Explain the race that lost these updates, how you would repair the data, and how you would change the cutover so that completeness is guaranteed rather than assumed.
DesignAdvanced7 min read

A platform team runs 40 PostgreSQL shards holding 4,096 logical buckets. Bucket moves are done by hand from a runbook, and some shards now hold twice the data and traffic of others.

Design an automatic rebalancer: how it measures imbalance, chooses which buckets move where, executes moves safely, and avoids making things worse.

Hot partitions and skew

Skew means data or load is not spread evenly: one tenant is huge, one key is wildly popular, or every current write targets today's partition. Averages hide it while one shard saturates. Understand how to measure skew, why adding shards does not help a single hot key, and the standard remedies: key salting, splitting hot counters, local caching of hot reads, and admission control.

ConceptFoundations7 min read

A sharded system reports average CPU of 35 percent across 32 shards, yet users see timeouts. Skew means that data or load is not spread evenly across partitions, and averages hide it.

Which kinds of skew exist, why do averages hide them, and which metrics would you put on a dashboard to see skew early?
DebuggingIntermediate8 min read

A stream processing job joins 200,000 click events per second with user profiles, keyed by user id across 48 partitions. One task runs 40 minutes behind while the others keep up; its input partition receives about 30 percent of all records, and the lagging records all have an empty user id.

Explain how this skew arises and how you would fix it, both in the job and at the source of the events.
ScenarioIntermediate7 min read

In a flash sale, 12,000 requests per second try to buy one discounted item with 5,000 units in stock. The stock row lives on one database shard; that shard reaches 100 percent CPU with lock waits, and most checkout requests time out.

Why would adding shards not help, and how would you redesign stock reservation so it scales without overselling?
DesignAdvanced8 min read

A sharded key-value store serves 2 million reads per second. During live sports events a handful of keys, such as the score of the current match, receive up to 400,000 reads per second each, and the shards that own them saturate while the cluster as a whole is mostly idle.

Design hot-key handling across the storage and client layers: how hot keys are detected, how their load is spread, and what consistency readers get.

Leader-follower replication

In leader-follower replication one node accepts writes and ships its change log to followers, which apply it in order and serve reads. It is the default in PostgreSQL, MySQL and many other systems. Understand how followers are created and kept in sync, how log retention limits how long they may be away, how replicas drift, and what asynchronous replication loses during failover.

InternalsFoundations7 min read

A PostgreSQL or MySQL primary takes a steady stream of writes, and the team needs a new read replica without stopping the primary or locking tables.

How is a new follower built from a consistent snapshot plus the replication log, and how does it know where in the log to start?
DebuggingFoundations7 min read

A PostgreSQL streaming replica was stopped for two days during a hardware repair. When it was started again, its log showed: FATAL: could not receive data from WAL stream: ERROR: requested WAL segment 000000010000004A000000C3 has already been removed.

What does this error mean, how do you get the replica back, and which settings decide how long a follower can be away?
DebuggingIntermediate6 min read

A MySQL read replica returns about 1,200 more active subscriptions than the primary for the same query. A week later replication on that replica stops with error 1062, duplicate entry for key PRIMARY.

How can a replica drift from its source, how do you find the differing rows, and how do you prevent drift?
ScenarioIntermediate7 min read

An order database used asynchronous replication. The primary crashed and the most current replica was promoted automatically, but the old primary had about 40 seconds of commits the replica never received, including orders already confirmed to customers by email.

New orders now receive ids that the lost orders had used, and those ids were already sent to the payment provider and to analytics. Explain why, and how you would recover and prevent it.
DesignAdvanced6 min read

A read-heavy platform runs one PostgreSQL primary with 18 streaming replicas in two regions for reporting and API reads. The primary's network egress has reached 9 Gbit/s at peak, and WAL sender processes compete with queries for CPU.

Redesign the replication topology so you can keep adding replicas, and explain the effect on lag, failover and operations.

Multi-leader and leaderless replication

Multi-leader replication lets several nodes accept writes and exchange them, for example one leader per region; leaderless replication lets any replica accept writes, with quorums deciding success. Both avoid a single write bottleneck but must handle conflicting writes and replicas that miss updates. Understand topologies, conflict sources, and the repair mechanisms such as hinted handoff, read repair and anti-entropy.

ConceptFoundations6 min read

In multi-leader replication more than one node accepts writes, and the leaders replicate to each other asynchronously, for example one leader per data center or one per device that works offline.

When is multi-leader replication worth its cost, which replication topologies exist between leaders, and what is its central problem?
InternalsFoundations6 min read

Leaderless stores in the Dynamo tradition, such as Cassandra and Riak, let any replica accept a write. A coordinator node sends each request to all replicas of the key and waits for enough of them to answer.

Walk through the write and read paths in such a store, and explain the three mechanisms that bring replicas back in sync: hinted handoff, read repair and anti-entropy repair.
DebuggingIntermediate6 min read

To give each region local writes, a team set up bidirectional MySQL replication between two regions, each primary replicating from the other. Within a week replication in one direction stopped with error 1062 (duplicate entry), and users report that some profile edits were silently undone.

Explain both problems, what you would change, and whether this setup should stay at all.
DebuggingIntermediate6 min read

A Cassandra node in a six-node cluster with replication factor 3 was down for six hours after a disk failure. It was restarted, and services that read and write at consistency level ONE returned stale and missing data for some customers over the following day.

Why did the node come back with gaps, why did ONE expose them, and what should the restart procedure and consistency settings have been?
LeadershipPrincipal7 min read

A team building a new core order platform proposes a leaderless, Dynamo-style database because it is always writable and never fails over. Another team prefers a leader-based database with consensus-based failover. The platform is expected to run for a decade.

As the senior technical leader, how do you evaluate the two replication models for this system, beyond the always-writable claim?

Quorums and tunable consistency

Quorum systems require W replicas to confirm a write and R to answer a read; when R + W exceeds N, reads overlap the latest successful write. Many stores let each request choose its level. Understand the failure arithmetic, multi-data-center levels such as LOCAL_QUORUM, why quorums are still not linearizable, and how replica placement across zones decides whether a quorum survives an outage.

ConceptFoundations6 min read

Quorum systems decide how many replicas must answer each read and write. The choice of N, W and R sets how many replica failures reads and writes survive, and replicas spread over data centers add further levels.

With N = 3 and N = 5, which W and R values give overlapping quorums and how many failed replicas does each tolerate? What do LOCAL_QUORUM and EACH_QUORUM mean with three replicas in each of two data centers?
DebuggingIntermediate6 min read

A service writes and reads at QUORUM on a Dynamo-style store with N = 3. An audit shows client A read version 7 of a record, and a moment later client B, also reading at QUORUM, received version 6.

How can two quorum reads go backwards in time even though R + W > N, and what settings or design changes prevent it?
ScenarioIntermediate6 min read

During a zone outage, writes at QUORUM with replication factor 3 failed with UnavailableException for about a third of the keys, although only one of three zones was down. The keyspace uses SimpleStrategy and every node reports the same rack.

Explain why losing one zone made some quorums impossible, and how you would fix replica placement without downtime.
DesignAdvanced7 min read

A ticketing platform runs on a leaderless store with three replicas per data center in two data centers. It serves seat-map browsing, seat reservation, purchase records and a high-volume view counter.

Choose consistency levels or mechanisms for each operation, explain the latency and availability cost of each choice, and say what you would keep out of this store.

Replication lag and read-your-writes

Asynchronous followers apply changes after the leader, so reads from them can be stale. Lag produces specific anomalies: not seeing your own write, seeing data go backwards between refreshes, and seeing effects before their causes. Understand guarantees such as read-your-writes, monotonic reads and consistent prefix, how lag is measured correctly, and how routing and tokens provide these guarantees.

ConceptFoundations6 min read

A question-and-answer app stores questions and answers in different partitions of a replicated store, and each partition replicates with its own lag. Readers sometimes see an answer before the question it answers.

What is the consistent prefix reads guarantee, why do partitioned stores break it, and how do designs restore it?
DebuggingFoundations6 min read

A forum reads comments from three asynchronous replicas behind a round-robin pool. Users report that a new comment appears, disappears on the next refresh, then appears again.

Which consistency guarantee is missing, why does round robin cause it, and what is the simplest fix?
DebuggingIntermediate6 min read

An alert on a PostgreSQL replica fired at 03:00 with replication lag of 25 minutes, measured as now() - pg_last_xact_replay_timestamp(), yet nothing was behind. On another night a MySQL replica reported Seconds_Behind_Source = 0 while reads from it were clearly minutes old.

Explain both false readings and how you would measure replication lag reliably.
ScenarioIntermediate6 min read

The order service writes an order to its PostgreSQL primary and publishes OrderCreated through an outbox. The shipping service consumes the event and calls GET /orders/{id}, which the order service answers from a replica. About 2 percent of these calls return 404.

Explain the race and compare the ways to fix it, with their costs.
LeadershipPrincipal6 min read

Your public API is moving reads to replicas in five regions to cut latency. Partners integrate by writing a resource and immediately reading it back, and some already report stale reads in the pilot.

As the senior technical leader, would you expose consistency to API clients, for example through consistency tokens, or hide it inside the platform? What do you commit to, and why?

Conflict resolution, LWW and CRDTs

When replicas accept concurrent writes, something must decide the final value. Last write wins keeps the highest timestamp and silently drops the rest; application merges and CRDTs combine concurrent updates so every replica converges. Understand what each approach loses, how CRDT merges guarantee convergence, which data types fit, and when a single writer is simpler.

ConceptFoundations6 min read

Last write wins (LWW) is the simplest conflict rule in replicated stores: every write carries a timestamp, and when replicas disagree the value with the highest timestamp is kept.

How does LWW work in a store such as Cassandra, what does it lose without any error, and for which kinds of data is it acceptable?
ConceptFoundations7 min read

Conflict-free replicated data types (CRDTs) are data structures that replicas can update independently and merge in any order, always reaching the same result without coordination.

Which properties must a CRDT's merge have, how do state-based and operation-based CRDTs differ, and how do a grow-only counter and an observed-remove set work?
CodingIntermediate8 min read

A like counter is updated in three regions that replicate asynchronously. The team wants each region to accept increments and decrements locally and merge the states it receives from the other regions.

Implement a PN-Counter in Java with increment, decrement, value and merge, and explain why merge takes the maximum per replica and what happens if a merge message is delivered twice.
DebuggingIntermediate7 min read

A shopping cart is stored as one JSON value per user in a multi-region store that resolves conflicts by last write wins. Customers using a phone and a laptop report that removed items come back and that items added on one device vanish.

Explain both symptoms and redesign the cart so concurrent edits merge correctly.
DesignAdvanced8 min read

A field-service mobile app must let technicians edit work orders offline for hours and sync when connected. Several technicians and the office may edit the same work order, including its notes, checklist and status.

Design the sync and conflict handling: what metadata is kept, how each field type merges, and where the server must still decide.

Multi-region data

Running data in several regions improves latency and survives regional outages, but cross-region round trips of tens to hundreds of milliseconds make strong consistency expensive. Designs range from one write region with remote replicas to home regions per user and active-active writes. Understand failover and failback, global constraints such as uniqueness, recovery point objectives, and data residency rules.

DebuggingIntermediate7 min read

After a regional outage the team promoted the cross-region PostgreSQL replica in eu-west and ran there for six hours. When us-east recovered, they pointed traffic back at the old primary. The next morning, orders created during those six hours are missing from reports.

Explain what went wrong in the failback, how you would recover the orders, and what the failback runbook should say.
DesignIntermediate6 min read

A social app runs active-active in three regions with asynchronous replication between them. Two users in different regions registered the same username within a second of each other, and both accounts now exist.

Design username uniqueness for this multi-region setup, and explain the latency and availability cost of each option.
ScenarioAdvanced6 min read

The disaster recovery target for a 6 TB order database is an RPO of 60 seconds, met by an asynchronous replica in a second region. Every night a batch job rewrites a 300 GB table; cross-region lag reaches 20 minutes and replication traffic costs grow each month.

How would you bring the RPO back within target during the batch window and control the cross-region cost?
DesignAdvanced6 min read

A payments app serves users in North America and Europe. To keep writes local and meet residency rules, each user's data will live in a home region with its own primary, instead of in one global primary.

Design the home-region model: how users are assigned and found, how a payment between a European and an American user works, and how a user moves between regions.
LeadershipPrincipal6 min read

A new market requires that citizens' personal data be stored and processed only inside the country. The product runs from two regions today, and many features, such as support tooling, search, fraud models and analytics, assume all data is in one place.

As the senior technical leader, how do you decide how to enter this market, and what architecture and organisational changes do you plan?