Sub topic 3
Central Counters and Auto-Increment: Simple, but a Bottleneck
This chapter assumes you know what a primary key is, have used an auto-increment column, and understand that a distributed system has several nodes that talk over a network and can fail independently. Here you will see why the simplest ID scheme works well on one machine and what limits it when many nodes need IDs.
The idea
A central counter is one place that holds the "next number". Every node that needs an ID asks that place, gets the current value, and the counter moves forward by one. In a relational database this is an auto-increment column or a sequence object.
CREATE TABLE orders (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id BIGINT NOT NULL
);
INSERT INTO orders (customer_id) VALUES (42) RETURNING id;The database guarantees that two concurrent inserts never receive the same value. It does this with an internal lock or an atomic increment on the counter. The IDs are small (8 bytes for a BIGINT), they are in insert order, and they index well.
What you get
- Uniqueness without effort. One authority hands out each number once.
- Compact IDs. A 64-bit integer is half the size of a UUID.
- Good index locality. New rows have the highest key, so inserts append to the right edge of the B-tree.
- Readable order. A larger ID usually means a later insert, which makes debugging easier.
Where it breaks
The same single authority causes three problems.
- Throughput ceiling. Every ID request goes through one counter. A single database can hand out many thousands of IDs per second, but all writers share that limit, and each request pays a network round trip.
- Availability. If the counter is down, no node can create new records. Adding a replica does not fix this by itself. A failover must make sure the new primary never reuses a value the old one already gave out.
- Latency across regions. A node in another region waits for a cross-region round trip on every insert.
Two common errors
Assuming IDs have no gaps. Sequences are not transactional. If a transaction asks for a value and then rolls back, that value is gone. A crash can also skip a cached block of values. Gaps are normal, so never use "the largest ID minus the count of rows" as a check, and do not build logic that expects consecutive IDs.
Assuming commit order matches ID order. Transaction A can get ID 10, transaction B can get ID 11, and B can commit first. A reader that polls with WHERE id > last_seen_id can see 11, move its cursor past 10, and then never see 10 when it commits later. Any "process new rows since the last ID" feature must account for this.
Multiple counters with strides
One way to remove the single point is to run several counters that never overlap. With N counters, counter k produces k, k+N, k+2N, .... MySQL supports this through auto_increment_increment and auto_increment_offset.
def counter_ids(offset, step, count):
# Counter 'offset' out of 'step' counters hands out offset, offset+step, ...
return [offset + i * step for i in range(count)]
print(counter_ids(1, 3, 4)) # [1, 4, 7, 10]
print(counter_ids(2, 3, 4)) # [2, 5, 8, 11]
print(counter_ids(3, 3, 4)) # [3, 6, 9, 12]IDs from different counters never collide, and each counter works alone. The costs are real, though:
| Concern | Effect |
|---|---|
| Adding a counter | You must change the step on every existing counter, and the new layout has to avoid values already issued. |
| Ordering | IDs are only roughly ordered across counters. |
| Failure of one counter | Its share of the ID space is unavailable until it recovers. |
Summary of the trade-off
A central counter gives the best IDs you can get: small, ordered, and unique. It pays for that with coordination on every insert. The next chapter shows how to keep the counter but ask it less often.
Exercise
Two transactions insert rows into a table with an auto-increment key. Transaction A gets ID 10 and Transaction B gets ID 11. B commits first, and a consumer reads all rows with id > 0, then stores 11 as its cursor. A commits afterward. What happens to row 10, and how could you avoid the problem?
Show answer
The consumer's next query (id > 11) never returns row 10, so it is skipped. Auto-increment values are assigned at insert time, not commit time. To avoid this, do not rely on the ID alone as a cursor. Options include re-reading a lagging window of recent IDs, polling by a commit-time column or log position, or using the database's change-log feature instead.
Exercise
A table uses three MySQL-style counters with step 3 and offsets 1, 2, and 3. Which counter issues ID 14, and what is the next ID that counter issues?
Show answer
Counter with offset 2 issues 14 (2, 5, 8, 11, 14). Its next ID is 17.