Photo Storage 2(Karat)

Difficulty: EASYCategory: HLDFrequency: 1Asked On 2025-05-01

Problem Statement

We are building a photo storage and sharing service where users can upload and share photos. To scale the storage infrastructure, we plan to shard user data across multiple machines. The current sharding strategy assigns users to servers based on the first letter of their username — for example, users with usernames starting with 'a' are stored on server 1, 'b' on server 2, and so on. This system is generalized to work with any number of servers by mapping chunks of the alphabet to each server. While simple and easy to implement, this design might not scale efficiently as our user base grows.

Solution

This alphabet-based sharding strategy can lead to uneven data distribution and hotspots. In real-world scenarios, usernames are not uniformly distributed across the alphabet. For example, names starting with 's', 'a', or 'm' might be far more common than those starting with 'q' or 'z'. As a result, some servers will end up handling much more load — in terms of storage, read/write operations, and network bandwidth — than others, causing imbalance and bottlenecks. Another issue arises when we need to scale the system by adding more servers. Repartitioning alphabet ranges is non-trivial and requires migrating large amounts of data from one server to another, leading to downtime or complex rebalancing logic.


A better approach would be to use consistent hashing, which maps users to servers based on a hash of their username. This distributes users more evenly across machines, regardless of the specific characters in their names. When the number of servers changes, consistent hashing ensures that only a small fraction of the users need to be moved, making it much more scalable and fault-tolerant. Additionally, using virtual nodes (or "vnodes") can help smooth out unevenness by assigning multiple hash slots per physical server. This ensures better load balancing and makes scaling operations less disruptive. Thus, switching from alphabetic sharding to a consistent hashing approach is a more robust and future-proof solution for this system.

Comments