ARCHIVED from builddistributedsystem.com on 2026-04-28 — URL: https://builddistributedsystem.com/tracks/identifier/tasks/task-2-2-1-bit-layout
TASK

Implementation

Twitter's Snowflake generates unique, roughly-sorted 64-bit IDs without coordination. The layout is:

| 1 bit unused | 41 bits timestamp | 10 bits machine ID | 12 bits sequence |
|     0        |   ms since epoch  |    0-1023          |    0-4095        |

Your task is to implement functions that:

  1. Compose a Snowflake ID from its three components (timestamp_ms, machine_id, sequence)
  2. Decompose a Snowflake ID back into its components
  3. Handle the Maelstrom generate workload using Snowflake IDs

Implement a generate message handler:

Request:  {"type": "generate", "msg_id": 1}
Response: {"type": "generate_ok", "in_reply_to": 1, "id": 7041429939834880}

And a decompose handler for debugging:

Request:  {"type": "decompose", "msg_id": 2, "id": 7041429939834880}
Response: {"type": "decompose_ok", "in_reply_to": 2, "timestamp_ms": 1678886400000, "machine_id": 1, "sequence": 0}

Sample Test Cases

Init and generate produces an IDTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"generate","msg_id":2}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
Two sequential generates produce different IDsTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"generate","msg_id":2}}
{"src":"c1","dest":"n1","body":{"type":"generate","msg_id":3}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}

Hints

Hint 1
Use left shift (<<) to position each component in the 64-bit integer
Hint 2
Timestamp goes in the top 41 bits, machine ID in the next 10, sequence in the bottom 12
Hint 3
Use bitwise OR (|) to combine the components
Hint 4
To extract components, use right shift (>>) and bitwise AND (&) with masks
Hint 5
Max IDs per ms per node = 2^12 = 4096
OVERVIEW

Theoretical Hub

Concept overview coming soon

Key Concepts

bit manipulationSnowflake IDbit layoutscalability
main.py
python
Implement Snowflake ID Bit Layout - The Identifier | Build Distributed Systems