← Study paths

Splitting the data

When one database node is not enough: how to partition, and the traps that follow.

6 blocks · about 33 min of reading · ends with Chat App

When you finish, you should be able to say

Pick a shard key for a given workload and defend it against the hot-partition question.

The route

6 blocks (2 fundamental, 3 senior, 1 staff), then the practice problem.

  1. Partition the dataFundamental
  2. Add nodes without remapping everythingSenior
  3. Fix a hot shardSenior
  4. Generate unique ids without a central counterFundamental
  5. Append-heavy, time-ordered rowsSenior
  6. Shard by regionStaff
  7. Chat App (WhatsApp / Messenger)
Scaling & loadStorage & data modellingFundamentalSeniorStaff
Read each block, then tick “I can explain this”: the path remembers where you are.Start with step 1
Your Chat App so far0 of 6 blocks in
Consistent hash ringconversation_id to chatshardConversation home regionnext step for multi-regionAlice's clientclient_msg_id on eachsendConnection serverAmazon EC2holds the WebSocketChat service shardAmazon EC2 Auto ScalingSnowflake id, seq =last + 1Message storeAmazon KeyspacesCassandra:conversation_id, seqUser inboxAmazon Keyspacespartitioned by user_idBusy group chatcap 1,024; last 50 inRedisStep 2: Add nodes without remapping everything2Step 6: Shard by region6Step 4: Generate unique ids without a central counter4Step 1: Partition the data1Step 5: Append-heavy, time-ordered rows5Step 1: Partition the data1Step 3: Fix a hot shard3send_messageforwardowner shardappendpending copyhot partitionhome region

Next, step 1 adds Message store, User inbox (outlined). A box fills in when you tick “I can explain this” on the block that introduces it; plain boxes come from the problem itself.

Each block has a diagram. Open one beside its step, or all of them at once.
  1. Partition the data

    Scaling & loadfundamental~6 min

    The core decision: what key splits the data, and what that makes expensive.

    One database holds more data or takes more writes than a single node can handle.

    Say it like this: Writes outgrow one node, so I partition by user id with consistent hashing, keep every hot-path query on a single shard, and treat cross-shard queries as a batch concern.

    Adds to the design: Message store, User inbox

    Check yourself: How do you pick the shard key?

    Start from the top two or three queries on the hot path and pick the column they all filter on. Then check it spreads load: high cardinality, no single value with a large share of traffic. If the two conflict, favour the hot path and handle the skew with salting or a dedicated shard.

    Read this block →

  2. Add nodes without remapping everything

    Scaling & loadsenior~5 min

    How to add a node without moving nearly every key.

    Modulo hashing (key % N) remaps almost every key when N changes.

    Say it like this: I partition the cache with consistent hashing and virtual nodes, so adding or losing a node remaps about one-Nth of the keys instead of nearly all of them.

    Adds to the design: Consistent hash ring

    Check yourself: How many virtual nodes per physical node and why?

    Around 100 to 200. With one position per node the slice sizes vary several-fold; with a few hundred positions the law of large numbers evens the slices to within a few percent. More than that costs lookup memory and ring-update time for little gain.

    Read this block →

  3. Fix a hot shard

    Scaling & loadsenior~5 min

    The failure every shard key eventually meets, and the fixes in order of cost.

    One partition takes most of the traffic (a celebrity, a popular tenant, a time-ordered key).

    Say it like this: The celebrity partition is taking most of the writes, so I salt the key into sub-partitions and read them back together, trading a wider read for an even write load.

    Adds to the design: Busy group chat

    Check yourself: How do you detect a hot partition before it becomes an incident?

    Per-partition throughput and latency metrics with an alert on the ratio of the hottest partition to the median. Many stores expose this directly, such as CloudWatch contributor insights for DynamoDB. Alert at 5× the median, which is well before saturation.

    Read this block →

  4. Generate unique ids without a central counter

    Storage & data modellingfundamental~5 min

    Sharded systems cannot use an auto-increment id; this is what they use instead.

    Auto-increment ids need one database; UUIDs are random and index poorly.

    Say it like this: Ids must be unique across many writers with no coordination on the hot path, so I use time-ordered ids like Snowflake or UUIDv7 that sort by creation time and index well.

    Adds to the design: Chat service shard

    Check yourself: Why are random UUIDs bad for a primary key?

    Random keys insert at random positions in a B-tree, so every insert touches a different page, causes splits and evicts useful pages from cache. Time-ordered keys append at the right edge, so inserts are sequential and the working set of index pages stays small.

    Read this block →

  5. Append-heavy, time-ordered rows

    Storage & data modellingsenior~6 min

    The store built for partition-key-plus-range access, and how to design its tables.

    Billions of rows written in order and read as ranges per key (messages, events, sensor data).

    Say it like this: The workload is append-heavy and every read is a range per key, so I use a wide-column store with the conversation as partition key and the sequence as clustering key, which makes each history read one sequential scan.

    Adds to the design: Message store

    Check yourself: How do you choose the partition key and clustering key?

    Partition key is whatever the hot query filters on exactly, so one query hits one partition. Clustering key is the order the query reads in, so the rows come back sorted with no sort step. Then check the partition stays under about 100 MB and a few hundred thousand rows; if not, add a time bucket to the partition key.

    Read this block →

  6. Shard by region

    Scaling & loadstaff~6 min

    Sometimes the natural split is geography; the extra problems that brings.

    Traffic is naturally local (a city, a country) and cross-region latency hurts.

    Say it like this: Rides never cross a city, so I shard every stateful component by region and keep each request inside one region, which gives local latency and makes a region outage a partial outage instead of a global one.

    Adds to the design: Conversation home region

    Check yourself: How does a request find its region?

    From the entity when there is one: a trip or driver id carries a region prefix, so the gateway routes on it. Otherwise from the client’s location or geo DNS for the first request, after which the response tells the client which region to use. The client caches the region and includes it on every call.

    Read this block →

  7. Putting it together

    How the blocks above combine into one design for Chat App. The numbers on the boxes are the steps that introduce each part.

    The chat app's sharded message path, assembled from the path
    Consistent hash ringconversation_id to chatshardConversation home regionnext step for multi-regionAlice's clientclient_msg_id on eachsendConnection serverAmazon EC2holds the WebSocketChat service shardAmazon EC2 Auto ScalingSnowflake id, seq =last + 1Message storeAmazon KeyspacesCassandra:conversation_id, seqUser inboxAmazon Keyspacespartitioned by user_idBusy group chatcap 1,024; last 50 inRedisStep 2: Add nodes without remapping everything2Step 6: Shard by region6Step 4: Generate unique ids without a central counter4Step 1: Partition the data1Step 5: Append-heavy, time-ordered rows5Step 1: Partition the data1Step 3: Fix a hot shard3send_messageforwardowner shardappendpending copyhot partitionhome region

    Each number is a step of this path; a box with two numbers is shaped by both blocks. The ring colour is the block's category, as on the route map. Boxes without a number come from the problem itself. Point at a step below, or at a bubble, to see where it appears.

    1. Partition the data
    2. Add nodes without remapping everything
    3. Fix a hot shard
    4. Generate unique ids without a central counter
    5. Append-heavy, time-ordered rows
    6. Shard by region

    Each conversation hashes to one chat shard, which mints its ids and sequence numbers and appends to a wide-column partition; pending copies go to per-user inbox partitions, busy groups are contained, and a home region per conversation is the next step.

    How each block shows up in the design

    • 1. Partition the data: messages are partitioned by conversation_id, so history and gap fills are one partition range scan, and the inbox is partitioned by user_id, so a reconnect is one scan; 4 TB a day only fits because no table lives on a single node.
    • 2. Add nodes without remapping everything: the chat service finds the shard that owns a conversation by consistent hashing on conversation_id, so adding a shard moves only a slice of conversations and each conversation keeps exactly one owner for its counter.
    • 3. Fix a hot shard: a busy group is a hot key for both its chat shard and its store partition, so group size is capped at 1,024, the last 50 or so messages of active chats are served from a Redis list, and very large groups switch from per-message pushes to pull.
    • 4. Generate unique ids without a central counter: message ids are Snowflake-style, minted on each shard without coordination and sortable by time, while the owning shard hands out seq as last_seq plus one for ordering, and the client's client_msg_id makes a retried send idempotent.
    • 5. Append-heavy, time-ordered rows: the message store is a wide-column store such as Cassandra keyed by conversation_id with seq as the clustering column, which turns a 700K per second write peak into sequential appends and history into ordered slices.
    • 6. Shard by region: going multi-region, each conversation gets a home region that holds its chat shard and its partition, so members nearby write locally and only chats that span regions pay the cross-region hop; this is the design's stated next step rather than part of the base design.
  8. ★

    Chat App (WhatsApp / Messenger)

    Now run the timed practice. The blocks above should appear in your answer without prompting; if one does not, that is the one to reread.

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2Connection serverCompute EngineAzure Virtual MachinesDigitalOcean Droplets, any VM or bare metal
Amazon EC2 Auto ScalingChat service shard, Service, Shard router, Writer, Reader, Chat serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon KeyspacesMessage store, User inbox, Owning replicasBigtableManaged Instance for Apache CassandraApache Cassandra, ScyllaDB
Amazon ElastiCacheMerged result cacheMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon AuroraPosts table, Global store (home), Local replicasAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB
Amazon Route 53Edge / geo DNSCloud DNSAzure DNS, Traffic ManagerCloudflare DNS, NS1