ARCHIVED from builddistributedsystem.com on 2026-04-28 — URL: https://builddistributedsystem.com/tracks/identifier/tasks/task-2-2-3-sequence-counter
TASK

Implementation

Within a single millisecond, each Snowflake node can generate up to 4096 unique IDs (12-bit sequence counter). When traffic bursts exceed this limit, the generator must handle sequence overflow gracefully.

Your task is to implement the sequence counter:

  1. Initialize to 0 at the start of each new millisecond
  2. Increment by 1 for each ID generated in the same millisecond
  3. On overflow (sequence > 4095), spin-wait until the next millisecond, then reset
  4. Track maximum sequence reached per millisecond for throughput analysis

Implement a generate_batch message that generates N IDs at once:

Request:  {"type": "generate_batch", "msg_id": 1, "count": 10}
Response: {"type": "generate_batch_ok", "in_reply_to": 1, "ids": [1, 2, 3, ...], "max_sequence": 9}

All generated IDs must be unique and monotonically increasing.

Sample Test Cases

Single generate worksTimeout: 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}}
Batch of 5 produces 5 unique 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_batch","msg_id":2,"count":5}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}

Hints

Hint 1
The sequence counter increments for each ID generated in the same millisecond
Hint 2
Reset the sequence to 0 when moving to a new millisecond
Hint 3
If the sequence overflows (>4095), wait until the next millisecond
Hint 4
Spin-waiting is acceptable here since millisecond transitions are fast
Hint 5
Track the max sequence reached for throughput analysis
OVERVIEW

Theoretical Hub

Concept overview coming soon

Key Concepts

sequence numberoverflow handlingspin waitthroughput limits
main.py
python
Implement Sequence Counter with Overflow Handling - The Identifier | Build Distributed Systems