Automation

Keys on shards

Build a deterministic modulo router for a batch of integer tenant IDs.

In production

Shard placement must be stable across processes. A randomized hash sends the same key to different shards after restart.

What it must return

Map each integer key to a shard index in [0, shard_count) with a deterministic modulo.

  • shard_count is positive; keys are nonnegative integers. Return a mapping with string shard indexes for nonempty shards only. Assign key % shard_count and preserve key order within each shard. Keep duplicates.
  • Do not mutate input values. Use the Python standard library only.

Edge cases

  • Modulo yields the shard index.
  • Do not use process-randomized hashes for an integer id.
  • shard_count is positive.

Signature

route_keys(keys, shard_count)

Hints

  1. Second hint

  2. A partial sketch

The reference solution opens after the last hint.

solution.py · Python

Loading editor…

Multiple shards

keys

[
  0,
  1,
  4,
  2,
  4
]

shard_count

3

Expected

{
  "0": [
    0
  ],
  "1": [
    1,
    4,
    4
  ],
  "2": [
    2
  ]
}

Each run uses a fresh Python runtime in this browser, with a 3-second limit and a Stop button. The first run downloads the runtime. 0 of 8 in Automation passed in Python on this device.

Next: Rollout batches